привет, возникла такая проблема, эти два аддона конфликтуют с друг другом, точнее gate maker вызывает смещение curve у progress track maker, сравни, есть ли между ними что-то связывающее? мб какая-то функция.
Вот первый код, второй я отправлю следующим сообщением:
import bpy
import os
import shutil
from xml.etree import ElementTree as ET
from bpy_extras.io_utils import ImportHelper, ExportHelper
from mathutils import Vector, Quaternion
from math import atan2, sin, cos, degrees, radians
bl_info = {
"name": "F1 AI Track Layout Maker",
"author": "AlonsoBeast",
"version": (1, 0),
"blender": (3, 3, 0),
"description": "Import and export F1 track layout from XML files",
"category": "Object",
}
for brake_line in brake_lines:
matching_hold_line = next((hold_line for hold_line in hold_lines if hold_line['brakeline_id'] == brake_line['brake_id']), None)
if matching_hold_line:
matched_min_speed_lines = [
min_speed_line for min_speed_line in min_speed_lines
if brake_line['gate_id'] < min_speed_line['gate_id'] < matching_hold_line['gate_id']
]
associated_lines.append({
'brake_line': brake_line,
'hold_line': matching_hold_line,
'min_speed_lines': matched_min_speed_lines
})
return associated_lines
def init_properties():
# Оригинальные свойства Сохраненеи Поколения
bpy.types.Scene.show_brake_lines = bpy.props.BoolProperty(
name="Show Brake Lines",
description="Expand to show brake lines details",
default=False
)
code
# Новые свойства для выбора целевых кривых
bpy.types.Scene.Track_Line_target = bpy.props.StringProperty(
name="Track Line Target",
default="Track_TARGET"
)
bpy.types.Scene.Start_Line_target = bpy.props.StringProperty(
name="Start Line Target",
default="Start_TARGET"
)
bpy.types.Scene.Trial_Line_target = bpy.props.StringProperty(
name="Trial Line Target",
default="Trial_TARGET"
)
bpy.types.Scene.Pit_CONE_target = bpy.props.StringProperty(
name="Pit Cone Target",
default="Pit_TARGET"
)
gate_empty = bpy.data.objects.new(gate_name, None)
gate_empty.empty_display_type = 'CONE' # Убедитесь, что форма - это конус
if is_splitter:
# Найдем все To_Gate связанные со сплиттерами
for link in splitter_data:
from_gate, to_gate, _ = link
# Если текущий gate_name соответствует to_gate
if gate_name == to_gate:
gate_empty.empty_display_size = 3.25 * 2.0 # Увеличиваем размер в 2.5 раза
gate_empty.scale[1] = 1.0 / 1.5 # Уменьшаем длину (высоту) в 1.5 раза
break
else:
gate_empty.empty_display_size = 3.25 # Обычный размер для других сплиттеров
else:
gate_empty.empty_display_size = 1.0 # Для обычных gate
gate_empty.location = (x, y_mirrored, z)
gate_empty["gate_number"] = i
normal_elem = gate.find('normal')
if normal_elem is not None:
normal = list(map(float, normal_elem.text.split()))
extract_normal_and_set_orientation(gate_empty, normal)
gate_empty['imported_normal'] = normal
gate_empty.rotation_euler.rotate_axis("Z", 3.14159)
context.collection.objects.link(gate_empty)
gate_objects.append(gate_empty)
class NewGateIDOperator(bpy.types.Operator):
"""Select single gate object to set as new"""
bl_idname = "f1.new_gate_id"
bl_label = "New Gate ID"
code
brake_line_id: bpy.props.IntProperty()
def execute(self, context):
selected_objects = context.selected_objects
if len(selected_objects) != 1 or not selected_objects[0].name.startswith("gate_"):
self.report({'WARNING'}, "Please select a single gate object")
return {'CANCELLED'}
new_gate_id = int(selected_objects[0].name.split("_")[1])
for line_data in brake_lines_data:
if line_data['brake_line']['brake_id'] == self.brake_line_id:
line_data['brake_line']['gate_id'] = new_gate_id
break
self.report({'INFO'}, f"Gate ID updated to: {new_gate_id}")
return {'FINISHED'}
class NewMinSpeedGateIDOperator(bpy.types.Operator):
"""Select single gate object to set as new for Min Speed"""
bl_idname = "f1.new_min_speed_gate_id"
bl_label = "New Min Speed Gate ID"
code
min_speed_line_id: bpy.props.IntProperty()
def execute(self, context):
selected_objects = context.selected_objects
if len(selected_objects) != 1 or not selected_objects[0].name.startswith("gate_"):
self.report({'WARNING'}, "Please select a single gate object")
return {'CANCELLED'}
new_gate_id = int(selected_objects[0].name.split("_")[1])
for line_data in brake_lines_data:
for min_speed_line in line_data['min_speed_lines']:
if min_speed_line['min_speed_line_id'] == self.min_speed_line_id:
min_speed_line['gate_id'] = new_gate_id
break
self.report({'INFO'}, f"Min Speed Gate ID updated to: {new_gate_id}")
return {'FINISHED'}
class NewHoldLineGateIDOperator(bpy.types.Operator):
"""Select single gate object to set as new for Hold Line"""
bl_idname = "f1.new_hold_line_gate_id"
bl_label = "New Hold Line Gate ID"
code
hold_line_id: bpy.props.IntProperty()
def execute(self, context):
selected_objects = context.selected_objects
if len(selected_objects) != 1 or not selected_objects[0].name.startswith("gate_"):
self.report({'WARNING'}, "Please select a single gate object")
return {'CANCELLED'}
new_gate_id = int(selected_objects[0].name.split("_")[1])
for line_data in brake_lines_data:
if line_data['hold_line']['hold_line_id'] == self.hold_line_id:
line_data['hold_line']['gate_id'] = new_gate_id
break
self.report({'INFO'}, f"Hold Line Gate ID updated to: {new_gate_id}")
return {'FINISHED'}
class SelectSplitterGate(bpy.types.Operator):
"""Select gate in scene"""
bl_idname = "f1.select_splitter_gate"
bl_label = "Select Splitter Gate"
code
gate_name: bpy.props.StringProperty()
def execute(self, context):
gate_object = bpy.data.objects.get(self.gate_name)
if gate_object is None:
self.report({'WARNING'}, "Object not found")
return {'CANCELLED'}
if gate_object not in bpy.context.selected_objects:
gate_object.select_set(True)
context.view_layer.objects.active = gate_object
return {'FINISHED'}
class SelectGateByName(bpy.types.Operator):
"""Select gate object by name in the scene"""
bl_idname = "f1.select_gate_by_name"
bl_label = "Select Gate by Name"
code
gate_name: bpy.props.StringProperty()
def execute(self, context):
gate_object = bpy.data.objects.get(self.gate_name)
if gate_object is None:
self.report({'WARNING'}, f"Gate object {self.gate_name} not found")
return {'CANCELLED'}
if gate_object not in bpy.context.selected_objects:
gate_object.select_set(True)
context.view_layer.objects.active = gate_object
return {'FINISHED'}
class CreateTargetSurface(bpy.types.Operator):
"""Create New Target Bezier Curves with Vector Handles"""
bl_idname = "f1.create_target_surface"
bl_label = "Create Target Surface"
code
def execute(self, context):
curve_names = ["Track_TARGET", "Start_TARGET", "Trial_TARGET", "Pit_TARGET"]
for name in curve_names:
if name not in bpy.data.objects:
# Создаем новую кривую типа CURVE
curve_data = bpy.data.curves.new(name=name, type='CURVE')
curve_data.dimensions = '3D'
spline = curve_data.splines.new('BEZIER')
spline.bezier_points.add(1) # Всего две точки (1 добавляется к уже существующей)
# Устанавливаем позиции и типы хэндлов для контрольных точек
start_point = spline.bezier_points[0]
start_point.co = Vector((0, 0, 0))
start_point.handle_left_type = 'VECTOR'
start_point.handle_right_type = 'VECTOR'
end_point = spline.bezier_points[1]
end_point.co = Vector((0, 20, 0)) # На 20 метров вперед по оси Y
end_point.handle_left_type = 'VECTOR'
end_point.handle_right_type = 'VECTOR'
# Создаем объект и добавляем его в текущую коллекцию
curve_object = bpy.data.objects.new(name, curve_data)
context.collection.objects.link(curve_object)
self.report({'INFO'}, "4 Target Curves Created with Straight Lines (Vector Handles)")
return {'FINISHED'}
from mathutils import Vector, Quaternion
from mathutils import Vector, Quaternion
from math import atan2, sin, cos, degrees
from mathutils import Vector, Quaternion
class CorrectGateOrientationOperator(bpy.types.Operator):
"""Corrects the orientation of gate objects to align with the curve"""
bl_idname = "f1.correct_way"
bl_label = "Correct Way"
code
source_curve_name: bpy.props.StringProperty()
def execute(self, context):
source_obj = bpy.data.objects.get(self.source_curve_name)
if not source_obj:
self.report({'ERROR'}, "Source curve not found")
return {'CANCELLED'}
source_spline = source_obj.data.splines[0]
selected_gates = [obj for obj in context.selected_objects if obj.name.startswith("gate_")]
if not selected_gates:
self.report({'WARNING'}, "No gate_* objects selected")
return {'CANCELLED'}
for gate_object in selected_gates:
# Найти ближайшую точку для каждого gate_object
min_distance = float('inf')
closest_point_index = 0
for i, point in enumerate(source_spline.bezier_points):
distance = (gate_object.location - point.co).length
if distance < min_distance:
min_distance = distance
closest_point_index = i
# Определяем направление между текущей и следующей точкой
current_point = source_spline.bezier_points[closest_point_index]
next_index = (closest_point_index + 1) % len(source_spline.bezier_points)
next_point = source_spline.bezier_points[next_index]
direction_vector = (next_point.co - current_point.co).normalized()
if direction_vector.length == 0:
continue
# Создаем кватернион из 'up' ориентации и направления
rotation_quaternion = direction_vector.to_track_quat('Z', 'Y')
# Разворачиваем объект на 180 градусов вокруг оси Z
flip_quaternion = Quaternion((0.0, 0.0, 1.0), radians(180))
rotation_quaternion = flip_quaternion @ rotation_quaternion
# Устанавливаем ненужные компоненты к нулю
rotation_quaternion.x = 0.0
rotation_quaternion.y = 0.0
# Применяем кватернион вращения к объекту
gate_object.rotation_mode = 'QUATERNION'
gate_object.rotation_quaternion = rotation_quaternion
# Отладочный вывод
print(f"Gate {gate_object.name}: Quaternion={rotation_quaternion}")
self.report({'INFO'}, "Corrected orientation for selected gate_* objects")
return {'FINISHED'}
class TransferShapeOperator(bpy.types.Operator):
"""Transfer Shape from Source to Target Curve"""
bl_idname = "f1.transfer_shape"
bl_label = "Transfer Shape"
code
source_curve_name: bpy.props.StringProperty()
target_curve_name: bpy.props.StringProperty()
def execute(self, context):
source_obj = bpy.data.objects.get(self.source_curve_name)
target_obj = bpy.data.objects.get(self.target_curve_name)
if not source_obj or not target_obj:
self.report({'ERROR'}, "Source or Target curve not found")
return {'CANCELLED'}
source_spline = source_obj.data.splines[0]
target_spline = target_obj.data.splines[0]
# Interpolate target bezier points to match source spline's points
total_source_points = len(source_spline.bezier_points)
total_target_points = len(target_spline.bezier_points) - 1
if total_target_points < 1:
self.report({'ERROR'}, "Target curve must have at least 2 control points")
return {'CANCELLED'}
# Use linear interpolation to calculate new positions along the target curve
for i, point in enumerate(source_spline.bezier_points):
t = i / (total_source_points - 1)
interpolated_index = int(t * total_target_points)
next_interpolated_index = min(interpolated_index + 1, total_target_points)
low_point = target_spline.bezier_points[interpolated_index].co
high_point = target_spline.bezier_points[next_interpolated_index].co
new_position = low_point.lerp(high_point, t * total_target_points - interpolated_index)
point.co = new_position
self.report({'INFO'}, f"Transferred shape to {self.source_curve_name}")
return {'FINISHED'}
class ImportF1TrackLayout(bpy.types.Operator, ImportHelper):
bl_idname = "import.f1_track_layout"
bl_label = "Import F1 Track Layout"
filename_ext = ".xml"
code
def execute(self, context):
global gate_objects, splitter_data, brake_lines_data
blend_dir = os.path.dirname(bpy.data.filepath)
temp_dir = os.path.join(blend_dir, "temp")
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
temp_file = os.path.join(temp_dir, f"{os.path.basename(self.filepath)}_temp.xml")
shutil.copy2(self.filepath, temp_file)
context.scene['temp_import_filepath'] = temp_file
success = self.import_from_temp_file(context, temp_file)
if success == {'FINISHED'}:
bpy.ops.object.update_gate_positions()
return success
def import_from_temp_file(self, context, temp_file):
try:
tree = ET.parse(temp_file)
root = tree.getroot()
gates = root.find('.//gates').findall('gate')
if not gates:
self.report({'ERROR'}, "No gates found in the XML file.")
return {'CANCELLED'}
splitter_data.clear()
gate_objects.clear()
brake_lines_data.clear()
links = root.find('.//links').findall('link')
splitter_ids = set()
for link in links:
from_gate = int(link.get('from_gate'))
to_gate = int(link.get('to_gate'))
if abs(from_gate - to_gate) > 1:
splitter_ids.update([from_gate, to_gate])
gate_name_from = f"gate_{from_gate:02}"
gate_name_to = f"gate_{to_gate:02}"
splitter_data.append((gate_name_from, gate_name_to, link))
fork_set = root.find('.//fork_sets/fork_set')
if not fork_set:
self.report({'ERROR'}, "No fork_set found in the XML file.")
return {'CANCELLED'}
split_gate_id = int(fork_set.get('gate_id'))
Trial_CIRCLE_id = int(fork_set.find('.//fork[@fork_position="1"]').get('link_id'))
split_link_elem = root.find('.//links/link[@id="0"]')
if split_link_elem is None:
self.report({'ERROR'}, "Link with ID 0 not found in the XML file.")
return {'CANCELLED'}
trial_split_gate_id = int(split_link_elem.get('from_gate'))
track_curve_data = bpy.data.curves.new(name="Track_Line_Curve", type='CURVE')
track_curve_data.dimensions = '3D'
track_spline = track_curve_data.splines.new('BEZIER')
trial_curve_data = bpy.data.curves.new(name="Trial_CIRCLE_Curve", type='CURVE')
trial_curve_data.dimensions = '3D'
trial_spline = trial_curve_data.splines.new('BEZIER')
pit_curve_data = bpy.data.curves.new(name="Pit_CONE_Curve", type='CURVE')
pit_curve_data.dimensions = '3D'
pit_spline = pit_curve_data.splines.new('BEZIER')
trial_line_curve_data = bpy.data.curves.new(name="Trial_Line_Curve", type='CURVE')
trial_line_curve_data.dimensions = '3D'
trial_line_spline = trial_line_curve_data.splines.new('BEZIER')
start_line_curve_data = bpy.data.curves.new(name="Start_Line_Curve", type='CURVE')
start_line_curve_data.dimensions = '3D'
start_line_spline = start_line_curve_data.splines.new('BEZIER')
track_points = [gate for gate in gates if int(gate.get('id')) <= split_gate_id]
trial_points = [gate for gate in gates if split_gate_id < int(gate.get('id')) <= Trial_CIRCLE_id]
pit_points = [gate for gate in gates if int(gate.get('id')) > Trial_CIRCLE_id]
trial_line_points = [gate for gate in trial_points if int(gate.get('id')) <= trial_split_gate_id]
start_line_points = [gate for gate in trial_points if int(gate.get('id')) > trial_split_gate_id]
track_spline.bezier_points.add(len(track_points) - 1)
trial_line_spline.bezier_points.add(len(trial_line_points) - 1)
start_line_spline.bezier_points.add(len(start_line_points) - 1)
pit_spline.bezier_points.add(len(pit_points) - 1)
for i, gate in enumerate(track_points):
position = gate.find('position')
if position is not None:
x, z, y = map(float, position.text.split())
y_mirrored = -y
control_point = track_spline.bezier_points[i]
control_point.co = (x, y_mirrored, z)
control_point.handle_left_type = 'VECTOR'
control_point.handle_right_type = 'VECTOR'
is_splitter = i in splitter_ids
create_gate_object(i, x, y_mirrored, z, gate, is_splitter, context)
offset = len(track_points)
for j, gate in enumerate(trial_line_points):
position = gate.find('position')
if position is not None:
x, z, y = map(float, position.text.split())
y_mirrored = -y
control_point = trial_line_spline.bezier_points[j]
control_point.co = (x, y_mirrored, z)
control_point.handle_left_type = 'VECTOR'
control_point.handle_right_type = 'VECTOR'
is_splitter = offset + j in splitter_ids
create_gate_object(offset + j, x, y_mirrored, z, gate, is_splitter, context)
offset += len(trial_line_points)
for k, gate in enumerate(start_line_points):
position = gate.find('position')
if position is not None:
x, z, y = map(float, position.text.split())
y_mirrored = -y
control_point = start_line_spline.bezier_points[k]
control_point.co = (x, y_mirrored, z)
control_point.handle_left_type = 'VECTOR'
control_point.handle_right_type = 'VECTOR'
is_splitter = offset + k in splitter_ids
create_gate_object(offset + k, x, y_mirrored, z, gate, is_splitter, context)
offset += len(start_line_points)
for l, gate in enumerate(pit_points):
position = gate.find('position')
if position is not None:
x, z, y = map(float, position.text.split())
y_mirrored = -y
control_point = pit_spline.bezier_points[l]
control_point.co = (x, y_mirrored, z)
control_point.handle_left_type = 'VECTOR'
control_point.handle_right_type = 'VECTOR'
is_splitter = offset + l in splitter_ids
create_gate_object(offset + l, x, y_mirrored, z, gate, is_splitter, context)
track_object = bpy.data.objects.new("Track_Line", track_curve_data)
trial_line_object = bpy.data.objects.new("Trial_Line", trial_line_curve_data)
start_line_object = bpy.data.objects.new("Start_Line", start_line_curve_data)
pit_object = bpy.data.objects.new("Pit_CONE", pit_curve_data)
context.collection.objects.link(track_object)
context.collection.objects.link(trial_line_object)
context.collection.objects.link(start_line_object)
context.collection.objects.link(pit_object)
bpy.context.view_layer.objects.active = track_object
track_object.select_set(True)
brake_lines = parse_brake_lines(root)
hold_lines = parse_hold_lines(root)
min_speed_lines = parse_min_speed_lines(root)
brake_lines_data.extend(associate_data(brake_lines, hold_lines, min_speed_lines))
self.report({'INFO'}, f"Imported track layout from: {temp_file}")
return {'FINISHED'}
except ET.ParseError as e:
self.report({'ERROR'}, f"XML parse error: {e}")
return {'CANCELLED'}
def restore_gate_objects(context):
temp_file = context.scene.get('temp_import_filepath', "")
if not temp_file or not os.path.isfile(temp_file):
return
code
try:
tree = ET.parse(temp_file)
root = tree.getroot()
gates = root.find('.//gates').findall('gate')
global gate_objects
gate_objects.clear()
for gate in gates:
gate_id = int(gate.get('id'))
gate_name = f"gate_{gate_id:02}"
gate_object = bpy.data.objects.get(gate_name)
if gate_object:
gate_objects.append(gate_object)
except ET.ParseError:
return
class ExportF1TrackLayout(bpy.types.Operator, ExportHelper):
bl_idname = "export.f1_track_layout"
bl_label = "Export F1 Track Layout"
filename_ext = ".xml"
code
filter_glob: bpy.props.StringProperty(
default="*.xml",
options={'HIDDEN'},
)
def execute(self, context):
def export_normal(gate_object):
# Извлекаем кватернион объекта
rotation_quat = gate_object.rotation_quaternion
# Предполагаем, что forward-вектор задан как (1, 0, 0)
example_forward_vector = Vector((1, 0, 0))
# Получаем нормаль из ориентации
normal_vector = rotation_quat @ example_forward_vector
# Инвертируем вектор нормали (разворачиваем его на 180 градусов)
flipped_normal = -normal_vector
# Поменять местами Y и Z, а X оставить положительным
return f"{-round(flipped_normal.x, 6)} {round(abs(flipped_normal.z), 6)} {round(flipped_normal.y, 6)}"
temp_file = context.scene.get('temp_import_filepath', "")
if not temp_file or not os.path.isfile(temp_file):
self.report({'ERROR'}, "Temporary file not found. Please import the track layout first.")
return {'CANCELLED'}
try:
tree = ET.parse(temp_file)
root = tree.getroot()
gates = root.find('.//gates').findall('gate')
for gate_object in gate_objects:
gate_id = gate_object.get("gate_number", None)
if gate_id is not None and gate_id < len(gates):
gate_elem = root.find(f".//gates/gate[@id='{gate_id}']")
if gate_elem is not None:
position = gate_elem.find('position')
if position is not None:
x, z, y = gate_object.location.x, gate_object.location.z, -gate_object.location.y
position.text = f"{round(x, 3)} {round(z, 3)} {round(y, 3)}"
# Используем новую функцию для экспорта нормали
normal_export = export_normal(gate_object)
normal_elem = gate_elem.find('normal')
if normal_elem is None:
normal_elem = ET.SubElement(gate_elem, 'normal')
normal_elem.set('format', 'float3')
normal_elem.text = normal_export
brake_lines_elem = root.find('.//brake_lines')
for line_data in brake_lines_data:
brake_line_elem = brake_lines_elem.find(f'brake_line[@id="{line_data["brake_line"]["brake_id"]}"]')
if brake_line_elem is not None:
gate_id_str = str(line_data["brake_line"]["gate_id"])
brake_line_elem.set('gate_id', gate_id_str)
min_speed_lines_elem = root.find('.//min_speed_lines')
for min_speed_line in line_data['min_speed_lines']:
min_speed_line_elem = min_speed_lines_elem.find(f'min_speed_line[@id="{min_speed_line["min_speed_line_id"]}"]')
if min_speed_line_elem is not None:
gate_id_str = str(min_speed_line["gate_id"])
min_speed_line_elem.set('gate_id', gate_id_str)
min_speed_line_elem.set('min_speed', f'{min_speed_line["min_speed"]:.2f}')
hold_lines_elem = root.find('.//hold_lines')
for line_data in brake_lines_data:
hold_line_elem = hold_lines_elem.find(f'hold_line[@id="{line_data["hold_line"]["hold_line_id"]}"]')
if hold_line_elem is not None:
gate_id_str = str(line_data["hold_line"]["gate_id"])
hold_line_elem.set('gate_id', gate_id_str)
tree.write(self.filepath)
self.report({'INFO'}, f"Successfully exported track layout to: {self.filepath}")
return {'FINISHED'}
except ET.ParseError as e:
self.report({'ERROR'}, f"XML parse error: {e}")
return {'CANCELLED'}
class UpdateGatePositions(bpy.types.Operator):
""""Update gate positions based on the Bezier control points"""
bl_idname = "object.update_gate_positions"
bl_label = "Update Gate Positions"
code
@classmethod
def poll(cls, context):
return any(name in bpy.data.objects for name in ["Track_Line", "Trial_Line", "Start_Line", "Pit_CONE"])
def execute(self, context):
restore_gate_objects(context)
num_track_points = len(bpy.data.objects["Track_Line"].data.splines[0].bezier_points) if "Track_Line" in bpy.data.objects else 0
num_trial_line_points = len(bpy.data.objects["Trial_Line"].data.splines[0].bezier_points) if "Trial_Line" in bpy.data.objects else 0
num_start_line_points = len(bpy.data.objects["Start_Line"].data.splines[0].bezier_points) if "Start_Line" in bpy.data.objects else 0
for curve_name in ["Track_Line", "Trial_Line", "Start_Line", "Pit_CONE"]:
if curve_name in bpy.data.objects:
curve_object = bpy.data.objects[curve_name]
control_points = curve_object.data.splines[0].bezier_points
for i, point in enumerate(control_points):
if curve_name == "Track_Line":
gate_index = i
elif curve_name == "Trial_Line":
gate_index = num_track_points + i
elif curve_name == "Start_Line":
gate_index = num_track_points + num_trial_line_points + i
else:
gate_index = num_track_points + num_trial_line_points + num_start_line_points + i
if gate_index < len(gate_objects):
gate_empty = gate_objects[gate_index]
if gate_empty:
gate_empty.location = (point.co.x, point.co.y, point.co.z)
return {'FINISHED'}
# Регистрация новых классов
bpy.utils.register_class(CreateTargetSurface) # Убедитесь, что этот класс зарегистрирован
bpy.utils.register_class(TransferShapeOperator)
def unregister():
# Отмена регистрации оригинальных классов
del bpy.types.Scene.show_brake_lines
bpy.utils.unregister_class(F1AITrackLayoutMakerPanel)
bpy.utils.unregister_class(ImportF1TrackLayout)
bpy.utils.unregister_class(ExportF1TrackLayout)
bpy.utils.unregister_class(UpdateGatePositions)
bpy.utils.unregister_class(SelectSplitterGate)
bpy.utils.unregister_class(SelectGateByName)
bpy.utils.unregister_class(NewGateIDOperator)
bpy.utils.unregister_class(NewMinSpeedGateIDOperator)
bpy.utils.unregister_class(NewHoldLineGateIDOperator)
code
# Отмена регистрации новых классов
del bpy.types.Scene.Track_Line_target
del bpy.types.Scene.Start_Line_target
del bpy.types.Scene.Trial_Line_target
del bpy.types.Scene.Pit_CONE_target
bpy.utils.unregister_class(CreateTargetSurface) # Убедитесь, что этот класс отпиан
bpy.utils.unregister_class(TransferShapeOperator)
if name == "main":
register()
Ваш код достаточно большой, и из текущего объяснения сложно сразу выделить точную причину конфликта между двумя аддонами. Однако, чтобы понять, вызывает ли аддон Gate Maker смещение кривых в аддоне Progress Track Maker, можно искать места, где происходят изменения Bezier Curves (кривых Безье) в коде этого аддона, и понять, предоставляют ли эти функции стороннюю модификацию, которая может потенциально конфликтовать с другим аддоном.
Вот несколько ключевых советов, чтобы определить возможную проблему:
1. Функции, изменяющие кривые Безье
В приведённом коде функции, которые каким-то образом воздействуют на кривые (Bezier Curves), могут быть причиной конфликта. Например:
CreateTargetSurface (создание новых кривых):
Эта функция явно создаёт новые кривые с фиксированными именами Track_TARGET, Start_TARGET, и т.д. Это может конфликтовать, если такие же имена используются в другом аддоне.
python
if name not in bpy.data.objects:
curve_data = bpy.data.curves.new(name=name, type='CURVE')
Это потенциально может вызвать смещение, если второй аддон пытается работать с теми же кривыми одновременно (создать или модифицировать). Будьте уверены, что названия объектов уникальны.
TransferShapeOperator (перенос формы кривой):
Эта функция явно модифицирует точки кривой. Если другой аддон использует те же кривые или точки в качестве основы, при переносе формы с одной кривой на другую может происходить случайное смещение.
python
for i, point in enumerate(source_spline.bezier_points):
...
point.co = new_position
Убедитесь, что эта операция выполняется только на целевых объектах/именах, чтобы не повлиять на работу других компонентов.
UpdateGatePositions (обновление позиций ворот):
В этой функции местоположение объектов отслеживается в связке с Bezier Curve. Если другой аддон использует эти же кривые, одновременное изменение может вызвать конфликт.
Например:
python
control_points = curve_object.data.splines[0].bezier_points
for i, point in enumerate(control_points):
gate_empty.location = (point.co.x, point.co.y, point.co.z)
Здесь обновляются координаты объектов из кривых. Если другой аддон также редактирует эти контрольные точки, это может привести к изменению положения объектов, к которым обращается этот код.
2. Пути решения
Проверить уникальность имён объектов или данных.
Конфликт может возникать, если несколько аддонов работают с одинаковыми именами объектов, например Track_Line, Trial_Line. Предложение:
Используйте уникальные имена объектов или создайте уникальный префикс для всех объектов, создаваемых вашим аддоном. Например:
python
curve_name = f"F1_{name}" # Префикс F1 для уникальности
Разделение областей взаимодействия между аддонами.
Разрешение конфликтов путём использования уникальных данных (на основе новой коллекции данных), чтобы код одного аддона никак не зависел от другого.
Логи изменений в консоли Blender.
Добавьте print везде, где ваши функции изменяют кривые или их точки. Например:
python
print(f"Point {i} updated: {point.co}")
Если другой аддон изменяет что-то ещё, это будет видно в логах.
Проверка конфликтующих областей.
Посмотрите, изменяет ли второй аддон кривые или объекты с такими же именами.
Если вы пришлёте второй код (Progress Track Maker), я смогу провести более глубокий анализ взаимодействия между двумя скриптами. Отправьте его следующим сообщением.
а вот второй код, посмотри в чем конфликтуют между собой:
import bpy
import xml.etree.ElementTree as ET
from bpy.props import StringProperty, IntProperty, BoolProperty
from bpy.types import Operator, Panel
from bpy_extras.io_utils import ImportHelper, ExportHelper
import tempfile
import shutil
from mathutils import Vector
class IMPORT_OT_ai_progress_track_maker(Operator, ImportHelper):
bl_idname = "import_mesh.ai_progress_track_maker"
bl_label = "Import AI Track XML"
filename_ext = ".xml"
filter_glob: StringProperty(default="*.xml", options={'HIDDEN'})
code
def execute(self, context):
try:
temp_filepath = tempfile.mktemp(suffix=".xml")
shutil.copy(self.filepath, temp_filepath)
context.scene.temp_ai_progress_file = temp_filepath
tree = ET.parse(self.filepath)
root = tree.getroot()
# Обработка gates
gates_element = root.find('gates')
if gates_element is not None:
left_points = []
right_points = []
for gate in gates_element.findall('gate'):
left = gate.find('left')
right = gate.find('right')
if left is None or right is None:
continue
left_coords = [float(x) for x in left.text.split()]
right_coords = [float(x) for x in right.text.split()]
left_points.append(left_coords)
right_points.append(right_coords)
left_spline = create_spline("LEFT_SPLINE", left_points)
right_spline = create_spline("RIGHT_SPLINE", right_points)
mirror_y_global(left_spline)
mirror_y_global(right_spline)
else:
self.report({'WARNING'}, "<gates> element not found in the file.")
# Обработка points для создания 2DMAP_SPLINE
points_element = root.find('points')
if points_element is not None:
for line in points_element.findall('line'):
if line.get("type") == "progress":
point_coords = []
for point in line.findall('point'):
position = point.find('position')
if position is not None:
coords = [float(x) for x in position.text.split()]
point_coords.append(coords)
twodmap_spline = create_spline("2DMAP_SPLINE", point_coords)
mirror_y_global(twodmap_spline) # Зеркальное отражение для 2DMAP_SPLINE
else:
self.report({'WARNING'}, "<points> element not found in the file.")
except ET.ParseError:
self.report({'ERROR'}, "Error reading XML file.")
return {'CANCELLED'}
return {'FINISHED'}
class EXPORT_OT_ai_progress_track_maker(Operator, ExportHelper):
bl_idname = "export_mesh.ai_progress_track_maker"
bl_label = "Export AI Track XML"
filename_ext = ".xml"
filter_glob: StringProperty(default="*.xml", options={'HIDDEN'})
code
def execute(self, context):
temp_filepath = context.scene.get("temp_ai_progress_file", "")
if not temp_filepath:
self.report({'ERROR'}, "Temporary file not found. Please re-import the file.")
return {'CANCELLED'}
self.update_xml_with_current_coordinates(temp_filepath)
shutil.copy(temp_filepath, self.filepath)
return {'FINISHED'}
def update_xml_with_current_coordinates(self, temp_filepath):
try:
tree = ET.parse(temp_filepath)
root = tree.getroot()
except ET.ParseError:
self.report({'ERROR'}, "Error reading temporary XML file.")
return {'CANCELLED'}
gates_element = root.find('gates')
if gates_element is None:
self.report({'ERROR'}, "Element <gates> not found in the file.")
return {'CANCELLED'}
left_spline = bpy.context.scene.objects.get("LEFT_SPLINE")
right_spline = bpy.context.scene.objects.get("RIGHT_SPLINE")
twodmap_spline = bpy.context.scene.objects.get("2DMAP_SPLINE")
if not left_spline or not right_spline or not twodmap_spline:
self.report({'ERROR'}, "Splines not found.")
return {'CANCELLED'}
left_points = left_spline.data.splines[0].points
right_points = right_spline.data.splines[0].points
twodmap_points = twodmap_spline.data.splines[0].points
for i, gate in enumerate(gates_element.findall('gate')):
left_element = gate.find('left')
right_element = gate.find('right')
if left_element is not None:
left_coords = left_points[i].co
left_text = f"{round(left_coords.x, 3)} {round(left_coords.z, 3)} {round(left_coords.y, 3)}"
left_element.text = left_text
if right_element is not None:
right_coords = right_points[i].co
right_text = f"{round(right_coords.x, 3)} {round(right_coords.z, 3)} {round(right_coords.y, 3)}"
right_element.text = right_text
points_element = root.find('points')
if points_element is None:
points_element = ET.SubElement(root, 'points')
for i, point in enumerate(twodmap_points):
# Изменяем порядок (XYZ -> XZY)
x_coord = point.co.x # Оставляем X
z_coord = point.co.z # Z уходит на Y
y_coord = point.co.y # Y уходит на Z
# Обновление или добавление точки в XML
if i < len(points_element.findall('line')[0].findall('point')):
point_element = points_element.find('line').findall('point')[i]
else:
point_element = ET.SubElement(points_element.find('line'), 'point', id=str(i))
position_element = point_element.find('position')
if position_element is not None:
position_element.text = f"{round(x_coord, 3)} {round(z_coord, 3)} {round(y_coord, 3)}"
else:
position_element = ET.SubElement(point_element, 'position', format="float3")
position_element.text = f"{round(x_coord, 3)} {round(z_coord, 3)} {round(y_coord, 3)}"
tree.write(temp_filepath, encoding='utf-8', xml_declaration=True)
def execute(self, context):
left_spline = bpy.context.scene.objects.get("LEFT_SPLINE")
right_spline = bpy.context.scene.objects.get("RIGHT_SPLINE")
if left_spline and right_spline:
for spline_object in (left_spline, right_spline):
bpy.context.view_layer.objects.active = spline_object
bpy.ops.object.mode_set(mode='EDIT')
spline = spline_object.data.splines.active
if spline and hasattr(spline, "points"):
if 0 <= self.split_gate_idx < len(spline.points):
for point in spline.points:
point.select = False
spline.points[self.split_gate_idx].select = True
return {'FINISHED'}
class SPLINE_OT_new_split_gate(Operator):
bl_idname = "spline.new_split_gate"
bl_label = "New Split Gate"
split_idx: IntProperty()
code
def execute(self, context):
left_spline = bpy.context.scene.objects.get("LEFT_SPLINE")
right_spline = bpy.context.scene.objects.get("RIGHT_SPLINE")
selected_gate_index = None
if left_spline and right_spline:
for spline_object in (left_spline, right_spline):
bpy.context.view_layer.objects.active = spline_object
bpy.ops.object.mode_set(mode='EDIT')
spline = spline_object.data.splines.active
if spline and hasattr(spline, "points"):
for i, point in enumerate(spline.points):
if point.select:
selected_gate_index = i
break
if selected_gate_index is not None:
temp_filepath = context.scene.get("temp_ai_progress_file", "")
if not temp_filepath:
self.report({'ERROR'}, "Temporary file not found.")
return {'CANCELLED'}
try:
tree = ET.parse(temp_filepath)
root = tree.getroot()
route_element = root.find('.//routes/route[@id="0"]')
if route_element:
split_element = route_element.find(f'.//split[@id="{self.split_idx}"]')
if split_element is not None:
split_element.set("gate", str(selected_gate_index))
tree.write(temp_filepath, encoding='utf-8', xml_declaration=True)
self.report({'INFO'}, f"Updated split {self.split_idx} with new gate index {selected_gate_index}")
except ET.ParseError:
self.report({'ERROR'}, "Error reading temporary XML file.")
return {'CANCELLED'}
else:
self.report({'ERROR'}, "No control point selected.")
return {'CANCELLED'}
return {'FINISHED'}
class TransferShapeOperator(Operator):
"""Transfer Shape from Target to Source Curve"""
bl_idname = "f1.transfer_shape"
bl_label = "Transfer Shape"
code
source_curve_name: StringProperty()
target_curve_name: StringProperty()
def execute(self, context):
source_obj = bpy.data.objects.get(self.source_curve_name)
target_obj = bpy.data.objects.get(self.target_curve_name)
if not source_obj or not target_obj:
self.report({'ERROR'}, f"Source or Target curve not found: {self.source_curve_name} or {self.target_curve_name}")
return {'CANCELLED'}
source_spline = source_obj.data.splines[0]
target_spline = target_obj.data.splines[0]
if not hasattr(source_spline, "points") or not hasattr(target_spline, "bezier_points"):
self.report({'ERROR'}, "Incorrect spline types")
return {'CANCELLED'}
num_source_points = len(source_spline.points)
num_target_points = len(target_spline.bezier_points)
if num_target_points == 0:
self.report({'ERROR'}, "Target spline has no points.")
return {'CANCELLED'}
# Перенос формы на основе контроля таргет кривой
for i in range(num_source_points):
# Рассчитываем нормализованный параметр t для исходного сплайна
t = i / (num_source_points - 1)
# Получаем интерполированные координаты для целевой кривой
new_position = self.interpolate_position(target_spline, t)
# Применяем зеркальное отражение
source_spline.points[i].co = (new_position[0], -new_position[1], new_position[2], 1.0)
self.report({'INFO'}, f"Transferred shape from {self.target_curve_name} to {self.source_curve_name}")
return {'FINISHED'}
def interpolate_position(self, spline, t):
points = spline.bezier_points
num_points = len(points)
if num_points == 0:
return Vector((0, 0, 0)) # Возвращаем нулевой вектор если не существует точек
# Рассчитываем индексы точек для интерполяции
i1 = int(t * (num_points - 1))
i2 = min(i1 + 1, num_points - 1)
p1 = points[i1].co
p2 = points[i2].co
alpha = (t * (num_points - 1)) % 1.0
vec1 = Vector(p1)
vec2 = Vector(p2)
return vec1.lerp(vec2, alpha)
class CreateTargetProgress(Operator):
"""Create Target Bezier Curves with Vector Handles"""
bl_idname = "f1.create_target_progress"
bl_label = "Create Target Surface"
bl_description = ("Adds two target splines in the scene. "
"Draw the track shape and use transfer shape progress "
"on them in the next section.")
code
def execute(self, context):
curve_names = ["LEFT_TARGET", "RIGHT_TARGET", "2DMAP_TARGET"]
for name in curve_names:
if name not in bpy.data.objects:
curve_data = bpy.data.curves.new(name=name, type='CURVE')
curve_data.dimensions = '3D'
spline = curve_data.splines.new('BEZIER')
spline.bezier_points.add(1)
start_point = spline.bezier_points[0]
start_point.co = Vector((0, 0, 0))
start_point.handle_left_type = 'VECTOR'
start_point.handle_right_type = 'VECTOR'
end_point = spline.bezier_points[1]
end_point.co = Vector((0, 20, 0))
end_point.handle_left_type = 'VECTOR'
end_point.handle_right_type = 'VECTOR'
curve_object = bpy.data.objects.new(name, curve_data)
context.collection.objects.link(curve_object)
self.report({'INFO'}, "Created LEFT_TARGET, RIGHT_TARGET, and 2DMAP_TARGET curves")
return {'FINISHED'}
def unregister():
del bpy.types.Scene.left_spline_target
del bpy.types.Scene.right_spline_target
del bpy.types.Scene.twodmap_spline_target
del bpy.types.Scene.temp_ai_progress_file
del bpy.types.Scene.show_gates
На первый взгляд, оба аддона в вашем коде явно работают с кривыми (Bezier или Polygon splines) и изменяют/переносят контрольные точки, что может создать конфликты. Вот мои основные наблюдения и возможные причины конфликта.
Основные причины конфликта
1. Имена кривых/сплайнов
Один из самых очевидных конфликтов - использование одинаковых или пересекающихся имен сплайнов/объектов в обоих аддонах.
Gate Maker аддон:
Использует кривые с именами Track_Line, Trial_Line, Start_Line, Pit_CONE, а также добавляет целевые кривые Track_TARGET, Start_TARGET, и другие.
Progress Track Maker:
Использует сплайны с именами LEFT_SPLINE, RIGHT_SPLINE, 2DMAP_SPLINE и целевые кривые LEFT_TARGET, RIGHT_TARGET, 2DMAP_TARGET.
Если один аддон создает или модифицирует кривую с именем, которое также используется другим аддоном, это может вызвать следующие проблемы:
Один аддон может удалить или переписать данные, которые критичны для выполнения другого.
Один аддон может изменять позиции точек в кривых, которые другой аддон использует для своих расчетов.
Рекомендация:
Убедитесь, что имена кривых, создаваемых в аддонах, уникальны. Вы можете добавить уникальные префиксы для имен:
python
# Пример для Gate Maker:
curve_name = f"GateMaker_{name}"
# Пример для Progress Track Maker:
spline_name = f"ProgressMaker_{name}"
2. Перехват или совместное использование "Активного объекта"
Некоторые функции (например, TRANSFER_OT_shape и различные операции с bpy.ops.object) изменяют "активный объект" (bpy.context.view_layer.objects.active). Это особенно очевидно в коде функции mirror_y_global и других операциях, таких как Transform -> Mirror.
Если оба аддона работают с объектами в активном режиме (например, ставят сплайны активными и изменяют точку симметрии или позиции), это может привести к нежелательному поведению:
Один аддон может изменить свойства объекта, которые важны для другого аддона.
Один аддон может очистить историю изменений или лишние данные, которые важны для выполнения операций другого аддона.
Эти операции меняют состояние объекта глобально и могут конфликтовать, если Gate Maker в то же время работает с той же кривой или объектом.
Рекомендация:
Минимизируйте использование bpy.ops в пользу прямого изменения данных через API. Например, вместо использования bpy.ops.transform.mirror, можно изменять координаты точек зеркально через код (это будет безопаснее).
3. Модификация точек в кривых
Оба аддона активно изменяют координаты точек в кривых (контрольные точки или точки сплайна). Один аддон может переместить точки, которые другой позже считает исходными.
Gate Maker:
python
# Transfer данных из одной кривой в другую
for i, point in enumerate(source_spline.bezier_points):
point.co = new_position
Progress Track Maker:
python
# Mirror координат точек
spline.points[i].co = (x, z, y, 1)
Конфликт возникает, если:
Gate Maker изменяет точки в Track_LINE или Trial_LINE, а Progress Track Maker пытается работать с их старым положением.
Progress Track Maker зеркально отражает точки LEFT_SPLINE, RIGHT_SPLINE, и это влияет на данные, которые Gate Maker позже рассчитывает/сохраняет.
Рекомендация:
Сделайте так, чтобы операции с точками всегда выполнялись для определённых объектов, экспортированные в другой домен, и проверяли текущее состояние сплайна перед модификацией.
4. Скрытые зависимости через глобальные переменные
Оба аддона используют ссылки на глобальные или сохраняемые данные в bpy.context.scene или XML-файлах. Если один аддон изменяет эти данные, другой может неожиданно прочитать их изменённое состояние.
Если оба аддона полагаются на состояние объекта с одинаковым именем, может произойти "перехват".
Как обойти эти конфликты?
Четкое разделение объектов:
Используйте уникальные названия объектов как для сплайнов (Track_Line, Start_Line) так и для гейтов (gate_01, LEFT_SPLINE) с префиксами:
python
my_unique_prefix = "Addon1_"
Работа с копиями данных, а не с общими объектами:
Вместо изменения кривой LEFT_SPLINE, создайте её локальную копию для работы.
Меньше зависимостей от "активного состояния":
Уберите зависимости от текущих выделений и активных объектов, явно передавайте объекты в функции.
Протокол изменений:
Добавьте отладочные сообщения (self.report() или print()), чтобы понять, какой аддон изменяет позицию точек, если будет конфликт.
Итог
Столкновение происходит в ключевых точках:
Кривые с общими именами.
Изменение точек кривых.
Использование активного объекта через bpy.ops.
Попробуйте внедрить вышеуказанные рекомендации — вероятно, они решат большинство конфликтов! Если после изменений конфликты сохранятся, дайте знать, уточнив симптомы (например, какая кривая/сплайн смещается).