Updating existing CSV spline by new CSV points?

Updating existing CSV spline by new CSV points?

Listrzmagorie
Participant Participant
183 Views
0 Replies
Message 1 of 1

Updating existing CSV spline by new CSV points?

Listrzmagorie
Participant
Participant

Hi,

Im struggling to find any way how to update existing spline created from CSV points by a new data set without loosing dependencies with the following geometries. I tried to delete the spline fit points and uploading new ones, but it freezes the program. Deleting and recreating the spline works but looses the dependencies. Im now out of ideas, so any help would be appreciated.

Thanks in advace

 

"""This file acts as the main module for this script.
Skript pro upload meridionalniho rezu generovanych ve Scilabu
Nutno puzit pouze se spravnym modelem ve Fusion
Pak je nutno ruzne opravit zavislosti
"""

import traceback
import adsk.core
import adsk.fusion
import adsk.cam
import csv
import tkinter as tk
from tkinter import filedialog
import os

# Initialize the global variables for the Application and UserInterface objects.
app = adsk.core.Application.get()
ui  = app.userInterface
design = app.activeProduct


def get_sketch_index_by_name(sketch_name):    #funkce pro urceni indexu sketche dle jeho jmena
    try:
        app = adsk.core.Application.get()
        design = app.activeProduct
        root_comp = design.rootComponent

        # Get all sketches in the root component
        sketches = root_comp.sketches

        # Iterate through sketches to find the one with the specified name
        for i in range(sketches.count):
            sketch = sketches.item(i)
            if sketch.name == sketch_name:
                return i  # Return the index (item number)

        # If no sketch with the given name is found
        return None
    except:
        return None

def read_csv_points(file_path):
    points = []
    try:
        with open(file_path, mode='r') as file:
            reader = csv.reader(file)
            for row in reader:
                if len(row) == 3:  # Assuming the CSV has x, y, z columns
                    points.append(adsk.core.Point3D.create(float(row[0]), float(row[1]), float(row[2])))
    except Exception as e:
        print(f"Error reading CSV file: {e}")
    return points

def update_sketch_profile(target_sketch_name, csv_file_path):
    try:
       # Access the root component
        root_comp = design.rootComponent
        # Read points from the CSV
        csv_points = read_csv_points(csv_file_path)
        if not csv_points:
            ui.messageBox("No valid points found in the CSV file.")
            return
        # Convert the list of points into an ObjectCollection
        point_collection = adsk.core.ObjectCollection.create()
        for point in csv_points:
            point_collection.add(point)

             
        # Get the item number for the sketch
        sketch_index = get_sketch_index_by_name(target_sketch_name)
        if sketch_index is None:
            ui.messageBox(f"Sketch '{target_sketch_name}' not found.")

        sketches = root_comp.sketches    
        target_sketch = sketches.item(sketch_index)  
        splines = target_sketch.sketchCurves.sketchFittedSplines

        if splines.count == 0:
            ui.messageBox("No splines found in the target sketch.")
            return      
        ''''
        # Delete the existing spline
        existing_spline = splines.item(0)  # Adjust the index for the correct spline
        existing_spline.deleteMe()

        # Create a new spline with the updated points
        new_spline = target_sketch.sketchCurves.sketchFittedSplines.add(point_collection)
        '''
    
        #nize je novy zpusob pouze modifikovani bodu splinu
        spline = splines[0]  # Modify the first spline in the sketch
              
        
        # Defer sketch computations to improve performance
        target_sketch.isComputeDeferred = True
        
        fit_points = spline.fitPoints
        for i in range(fit_points.count - 1, -1, -1):  # Start from the last index
            fit_points.item(i).deleteMe()
        
        for point in point_collection:
            spline.fitPoints.add(point)
        
       # Reactivate sketch computations
        target_sketch.isComputeDeferred = False
        
        # Update the sketch to reflect changes
        #target_sketch.sketchCurves.addFitPointSpline(csv_points)          
      
    except:  #pylint:disable=bare-except
        # Write the error message to the TEXT COMMANDS window.
        app.log(f'Failed:\n{traceback.format_exc()}')
        ui.messageBox(f"Failed:\n{traceback.format_exc()}")
    return None


def run(_context: str):
    """This function is called by Fusion when the script is run."""

    try:
        # Your code goes here.
        ui.messageBox(f'"{app.activeDocument.name}" is the active Document.')
        #dialog pro otevreni adresare se soubory krivek kompresoru
        root = tk.Tk()
        root.withdraw()  # Hide the main tkinter window
        folder_path = filedialog.askdirectory(title="Select Folder with CSV Files")
        print(f"Selected folder: {folder_path}")
                
        # Access the root component
        csv_file_path1 = os.path.join(folder_path, 'Meridian_pata.csv')
        csv_file_path2 = os.path.join(folder_path, 'Meridian_spicka.csv')
           
            # Suspend updates
        #design.freezeUpdates = True

        update_sketch_profile('merid-pata',csv_file_path1)
        update_sketch_profile('merid-spicka',csv_file_path2)
           
            # Resume updates
        #design.freezeUpdates = False

        ui.messageBox("Curve updated from CSV successfully!")
    except:  #pylint:disable=bare-except
        # Write the error message to the TEXT COMMANDS window.
        app.log(f'Failed:\n{traceback.format_exc()}')
        ui.messageBox(f"Failed:\n{traceback.format_exc()}")
            # Resume updates
        #design.freezeUpdates = False

 

0 Likes
184 Views
0 Replies
Replies (0)