# smedgeRender_C4D.py
# Smedge Submitter Script for Cinema 4D
#
# Smedge
# Copyright Uberware. All Rights Reserved.


#  Initialize
import c4d
import subprocess
import os
import sys
from c4d import documents,storage,gui


#  Set this to the path to the Smedge executable
#       ****   NOTE   ****
#  You need to adjust this path to be correct for your system. The default paths
#  below are often where Smedge is installed for Windows and Mac
#       ******************
if c4d.GeGetCurrentOS() == c4d.OPERATINGSYSTEM_WIN:
    smedgePath = '"C:\\Program Files\\Smedge\\Submit.exe"'
else:
    smedgePath = '/Applications/Smedge.app/Contents/MacOS/Submit'


#  Get the document info
fps = doc.GetFps()
scenename = doc.GetDocumentName()
scenepath = doc.GetDocumentPath()
rd = doc.GetActiveRenderData()
sf = (rd[ c4d.RDATA_FRAMEFROM ]).GetFrame( fps )
ef = (rd[ c4d.RDATA_FRAMETO ]).GetFrame( fps )
#	Get the output format, because C4D doesn't display the file path it creates
def ext(x):
	return {
		c4d.FILTER_TIF: '.tif',
		c4d.FILTER_TGA: '.tga',
		c4d.FILTER_BMP: '.bmp',
		c4d.FILTER_PICT: '.pict',
		c4d.FILTER_JPG: '.jpg',
		c4d.FILTER_RLA: '.rla',
		c4d.FILTER_RPF: '.rpf',
		c4d.FILTER_B3D: '.b3d',
		c4d.FILTER_TIF_B3D: '.tif',
		c4d.FILTER_PSB: '.psb',
		c4d.FILTER_HDR: '.hdr',
		c4d.FILTER_PNG: '.png',
		c4d.FILTER_IES: '.ies',
		}.get(x,'')
def format(x,y):
	if x == c4d.RDATA_NAMEFORMAT_0:
		return '%04d' + ext(y)
	elif x == c4d.RDATA_NAMEFORMAT_1:
		return '%04d'
	elif x == c4d.RDATA_NAMEFORMAT_2:
		return '.%04d'
	elif x == c4d.RDATA_NAMEFORMAT_3:
		return '%03d' + ext(y)
	elif x == c4d.RDATA_NAMEFORMAT_4:
		return '%03d'
	elif x == c4d.RDATA_NAMEFORMAT_5:
		return '.%03d'
	elif x == c4d.RDATA_NAMEFORMAT_6:
		return '.%04d.' + ext(y)
	else:
		return ''
output = rd[ c4d.RDATA_PATH ] + format( rd[ c4d.RDATA_NAMEFORMAT ], rd[ c4d.RDATA_FORMAT ] )

#  Get the whole filename by combining scene path and scene name
fn = os.path.join( scenepath, scenename )

#  Build the command line
sj  = str( smedgePath )
sj += " Script"
sj += " -Type Cinema 4D"
sj += " -Scene " + str( fn )
sj += " -Range " + str( sf ) + "-" + str( ef )
sj += " -Name " + str( scenename )
sj += " -InitImageFormat " + output
#  other options you may want to add (uncomment them if you want to use them):
#  this sets the packet size (how many frames are rendered by one machine at one time)
#sj += " -PacketSize 10"
#  this sets the pool. You can use pool names or IDs
#sj += " -Pool Pool Name"
#  this sets the number of cores to use for each render (by default it will use all available)
#sj += " -CPUs 4"
#  this sets the job to be submitted paused
#sj += " -Paused"


#  Time to do it!
print( sj )
try:
    subprocess.call( sj )
except:
    gui.MessageDialog( "Command:\n\n" + sj + "\n\nFailed:\n" + str( sys.exc_info()[1] ) )
else:
    gui.MessageDialog( "Submitted to Smedge!" )
