def get_versioned_filename(base_name, directory, extension='.csv'):
# Format the initial filename
filename = f"{base_name}_V{version}{extension}"
# Construct the full path to check if it exists
full_path = os.path.join(directory, filename)
# Loop until a unique filename is found
while os.path.exists(full_path):
version += 1 # Increment the version
filename = f"{base_name}_V{version}{extension}" # Update the filename with the new version
full_path = os.path.join(directory, filename) # Update the full path
return full_path # Return the unique file path with version
def write_frame_data(filePath, frame_data):
with open(filePath, "a") as file:
# Join all red values into a single line
line = ",".join(frame_data)
# Get the active Cinema 4D document
doc = c4d.documents.GetActiveDocument()
# Find the Matrix object by name 'Export'
matrix_object = doc.SearchObject('Export')
print("Matrix object named 'Export' not found")
# Get the grid resolution vector
grid_resolution = matrix_object[c4d.MG_GRID_RESOLUTION]
if grid_resolution is None:
print("Grid resolution data not found")
x_grid_size = int(grid_resolution.x)
z_grid_size = int(grid_resolution.z)
startFrame = doc.GetLoopMinTime().GetFrame(doc.GetFps())
endFrame = doc.GetLoopMaxTime().GetFrame(doc.GetFps())
numberOfFrames = endFrame - startFrame + 1
base_directory = "H:/My Drive/02_Projects/41_SPTF_FCBNY Spotify/01_Production/C4D/240205_WriteValuesToExcel/Written"
base_name = f"single_channel_values_{numberOfFrames}_frames_{x_grid_size}x{z_grid_size}grid"
# Use versioning function to get a unique file path
filePath = get_versioned_filename(base_name, base_directory)
for frame in range(startFrame, endFrame + 1):
doc.SetTime(c4d.BaseTime(frame, doc.GetFps()))
c4d.DrawViews(c4d.DA_ONLY_ACTIVE_VIEW | c4d.DA_NO_THREAD | c4d.DA_STATICBREAK)
c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
doc.ExecutePasses(None, True, True, True, c4d.BUILDFLAGS_0)
md = c4d.modules.mograph.GeGetMoData(matrix_object)
print(f"MoGraph data not found for frame {frame}")
colors = md.GetArray(c4d.MODATA_COLOR)
print(f"Color data not found for frame {frame}")
frame_data = [f"{max(0, min(int(color.x*255), 255))}" for color in colors]
write_frame_data(filePath, frame_data)
print(f"Red color data for frames {startFrame} to {endFrame} written to file {filePath}")