Enforce quotes consistency.
[OpenColorIO-Configs.git] / aces_1.0.0 / python / aces_ocio / create_aces_config.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 """
5 Defines objects creating the *ACES* configuration.
6 """
7
8 import math
9 import numpy
10 import os
11 import pprint
12 import shutil
13 import string
14 import sys
15
16 # TODO: This restores the capability of running the script without having
17 # added the package to PYTHONPATH, this is ugly and should ideally replaced by
18 # dedicated executable in a /bin directory.
19 sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
20
21 import PyOpenColorIO as OCIO
22
23 import aces_ocio.create_arri_colorspaces as arri
24 import aces_ocio.create_canon_colorspaces as canon
25 import aces_ocio.create_red_colorspaces as red
26 import aces_ocio.create_sony_colorspaces as sony
27 from aces_ocio.generate_lut import (
28     generate_1d_LUT_from_CTL,
29     generate_3d_LUT_from_CTL,
30     write_SPI_1d)
31 from aces_ocio.process import Process
32 from aces_ocio.utilities import ColorSpace, mat44_from_mat33
33
34 __author__ = 'ACES Developers'
35 __copyright__ = 'Copyright (C) 2014 - 2015 - ACES Developers'
36 __license__ = ''
37 __maintainer__ = 'ACES Developers'
38 __email__ = 'aces@oscars.org'
39 __status__ = 'Production'
40
41 __all__ = ['ACES_OCIO_CTL_DIRECTORY_ENVIRON',
42            'ACES_OCIO_CONFIGURATION_DIRECTORY_ENVIRON',
43            'set_config_default_roles',
44            'write_config',
45            'generate_OCIO_transform',
46            'create_config',
47            'generate_LUTs',
48            'generate_baked_LUTs',
49            'create_config_dir',
50            'get_transform_info',
51            'get_ODT_info',
52            'get_LMT_info',
53            'create_ACES_config',
54            'main']
55
56 ACES_OCIO_CTL_DIRECTORY_ENVIRON = 'ACES_OCIO_CTL_DIRECTORY'
57 ACES_OCIO_CONFIGURATION_DIRECTORY_ENVIRON = 'ACES_OCIO_CONFIGURATION_DIRECTORY'
58
59
60 def set_config_default_roles(config,
61                              color_picking='',
62                              color_timing='',
63                              compositing_log='',
64                              data='',
65                              default='',
66                              matte_paint='',
67                              reference='',
68                              scene_linear='',
69                              texture_paint=''):
70     """
71     Sets given *OCIO* configuration default roles.
72
73     Parameters
74     ----------
75     config : config
76         *OCIO* configuration.
77     color_picking : str or unicode
78         Color picking role title.
79     color_timing : str or unicode
80         Color timing role title.
81     compositing_log : str or unicode
82         Compositing log role title.
83     data : str or unicode
84         Data role title.
85     default : str or unicode
86         Default role title.
87     matte_paint : str or unicode
88         Matte painting role title.
89     reference : str or unicode
90         Reference role title.
91     scene_linear : str or unicode
92         Scene linear role title.
93     texture_paint : str or unicode
94         Texture painting role title.
95
96     Returns
97     -------
98     bool
99          Definition success.
100     """
101
102     if color_picking:
103         config.setRole(OCIO.Constants.ROLE_COLOR_PICKING, color_picking)
104     if color_timing:
105         config.setRole(OCIO.Constants.ROLE_COLOR_TIMING, color_timing)
106     if compositing_log:
107         config.setRole(OCIO.Constants.ROLE_COMPOSITING_LOG, compositing_log)
108     if data:
109         config.setRole(OCIO.Constants.ROLE_DATA, data)
110     if default:
111         config.setRole(OCIO.Constants.ROLE_DEFAULT, default)
112     if matte_paint:
113         config.setRole(OCIO.Constants.ROLE_MATTE_PAINT, matte_paint)
114     if reference:
115         config.setRole(OCIO.Constants.ROLE_REFERENCE, reference)
116     if scene_linear:
117         config.setRole(OCIO.Constants.ROLE_SCENE_LINEAR, scene_linear)
118     if texture_paint:
119         config.setRole(OCIO.Constants.ROLE_TEXTURE_PAINT, texture_paint)
120
121     return True
122
123
124 def write_config(config, config_path, sanity_check=True):
125     """
126     Writes the configuration to given path.
127
128     Parameters
129     ----------
130     parameter : type
131         Parameter description.
132
133     Returns
134     -------
135     type
136          Return value description.
137     """
138
139     if sanity_check:
140         try:
141             config.sanityCheck()
142         except Exception, e:
143             print e
144             print 'Configuration was not written due to a failed Sanity Check'
145             return
146             # sys.exit()
147
148     file_handle = open(config_path, mode='w')
149     file_handle.write(config.serialize())
150     file_handle.close()
151
152
153 def generate_OCIO_transform(transforms):
154     """
155     Object description.
156
157     Parameters
158     ----------
159     parameter : type
160         Parameter description.
161
162     Returns
163     -------
164     type
165          Return value description.
166     """
167
168     # print('Generating transforms')
169
170     interpolation_options = {
171         'linear': OCIO.Constants.INTERP_LINEAR,
172         'nearest': OCIO.Constants.INTERP_NEAREST,
173         'tetrahedral': OCIO.Constants.INTERP_TETRAHEDRAL
174     }
175     direction_options = {
176         'forward': OCIO.Constants.TRANSFORM_DIR_FORWARD,
177         'inverse': OCIO.Constants.TRANSFORM_DIR_INVERSE
178     }
179
180     ocio_transforms = []
181
182     for transform in transforms:
183         if transform['type'] == 'lutFile':
184             ocio_transform = OCIO.FileTransform(
185                 src=transform['path'],
186                 interpolation=interpolation_options[
187                     transform['interpolation']],
188                 direction=direction_options[transform['direction']])
189             ocio_transforms.append(ocio_transform)
190         elif transform['type'] == 'matrix':
191             ocio_transform = OCIO.MatrixTransform()
192             # MatrixTransform member variables can't be initialized directly.
193             # Each must be set individually.
194             ocio_transform.setMatrix(transform['matrix'])
195
196             if 'offset' in transform:
197                 ocio_transform.setOffset(transform['offset'])
198
199             if 'direction' in transform:
200                 ocio_transform.setDirection(
201                     direction_options[transform['direction']])
202
203             ocio_transforms.append(ocio_transform)
204         elif transform['type'] == 'exponent':
205             ocio_transform = OCIO.ExponentTransform()
206             ocio_transform.setValue(transform['value'])
207             ocio_transforms.append(ocio_transform)
208         elif transform['type'] == 'log':
209             ocio_transform = OCIO.LogTransform(
210                 base=transform['base'],
211                 direction=direction_options[transform['direction']])
212
213             ocio_transforms.append(ocio_transform)
214         else:
215             print('Ignoring unknown transform type : %s' % transform['type'])
216
217     # Build a group transform if necessary
218     if len(ocio_transforms) > 1:
219         transform_G = OCIO.GroupTransform()
220         for transform in ocio_transforms:
221             transform_G.push_back(transform)
222         transform = transform_G
223
224     # Or take the first transform from the list
225     else:
226         transform = ocio_transforms[0]
227
228     return transform
229
230
231 def create_config(config_data, nuke=False):
232     """
233     Object description.
234
235     Parameters
236     ----------
237     parameter : type
238         Parameter description.
239
240     Returns
241     -------
242     type
243          Return value description.
244     """
245
246     # Create the config
247     config = OCIO.Config()
248
249     #
250     # Set config wide values
251     #
252     config.setDescription('An ACES config generated from python')
253     config.setSearchPath('luts')
254
255     #
256     # Define the reference color space
257     #
258     reference_data = config_data['referenceColorSpace']
259     print('Adding the reference color space : %s' % reference_data.name)
260
261     # Create a color space
262     reference = OCIO.ColorSpace(
263         name=reference_data.name,
264         bitDepth=reference_data.bit_depth,
265         description=reference_data.description,
266         equalityGroup=reference_data.equality_group,
267         family=reference_data.family,
268         isData=reference_data.is_data,
269         allocation=reference_data.allocation_type,
270         allocationVars=reference_data.allocation_vars)
271
272     # Add to config
273     config.addColorSpace(reference)
274
275     #
276     # Create the rest of the color spaces
277     #
278     for colorspace in sorted(config_data['colorSpaces']):
279         print('Creating new color space : %s' % colorspace.name)
280
281         ocio_colorspace = OCIO.ColorSpace(
282             name=colorspace.name,
283             bitDepth=colorspace.bit_depth,
284             description=colorspace.description,
285             equalityGroup=colorspace.equality_group,
286             family=colorspace.family,
287             isData=colorspace.is_data,
288             allocation=colorspace.allocation_type,
289             allocationVars=colorspace.allocation_vars)
290
291         if colorspace.to_reference_transforms != []:
292             print('Generating To-Reference transforms')
293             ocio_transform = generate_OCIO_transform(
294                 colorspace.to_reference_transforms)
295             ocio_colorspace.setTransform(
296                 ocio_transform,
297                 OCIO.Constants.COLORSPACE_DIR_TO_REFERENCE)
298
299         if colorspace.from_reference_transforms != []:
300             print('Generating From-Reference transforms')
301             ocio_transform = generate_OCIO_transform(
302                 colorspace.from_reference_transforms)
303             ocio_colorspace.setTransform(
304                 ocio_transform,
305                 OCIO.Constants.COLORSPACE_DIR_FROM_REFERENCE)
306
307         config.addColorSpace(ocio_colorspace)
308
309         print('')
310
311     #
312     # Define the views and displays
313     #
314     displays = []
315     views = []
316
317     # Generic display and view setup
318     if not nuke:
319         for display, view_list in config_data['displays'].iteritems():
320             for view_name, colorspace in view_list.iteritems():
321                 config.addDisplay(display, view_name, colorspace.name)
322                 if not (view_name in views):
323                     views.append(view_name)
324             displays.append(display)
325     # A Nuke specific set of views and displays
326     #
327     # XXX
328     # A few names: Output Transform, ACES, ACEScc, are hard-coded here.
329     # Would be better to automate.
330     #
331     else:
332         for display, view_list in config_data['displays'].iteritems():
333             for view_name, colorspace in view_list.iteritems():
334                 if (view_name == 'Output Transform'):
335                     view_name = 'View'
336                     config.addDisplay(display, view_name, colorspace.name)
337                     if not (view_name in views):
338                         views.append(view_name)
339             displays.append(display)
340
341         config.addDisplay('linear', 'View', 'ACES2065-1')
342         displays.append('linear')
343         config.addDisplay('log', 'View', 'ACEScc')
344         displays.append('log')
345
346     # Set active displays and views
347     config.setActiveDisplays(','.join(sorted(displays)))
348     config.setActiveViews(','.join(views))
349
350     #
351     # Need to generalize this at some point
352     #
353
354     # Add Default Roles
355     set_config_default_roles(
356         config,
357         color_picking=reference.getName(),
358         color_timing=reference.getName(),
359         compositing_log=reference.getName(),
360         data=reference.getName(),
361         default=reference.getName(),
362         matte_paint=reference.getName(),
363         reference=reference.getName(),
364         scene_linear=reference.getName(),
365         texture_paint=reference.getName())
366
367     # Check to make sure we didn't screw something up
368     config.sanityCheck()
369
370     return config
371
372
373 def generate_LUTs(odt_info,
374                   lmt_info,
375                   shaper_name,
376                   aces_CTL_directory,
377                   lut_directory,
378                   lut_resolution_1d=4096,
379                   lut_resolution_3d=64,
380                   cleanup=True):
381     """
382     Object description.
383
384     Parameters
385     ----------
386     parameter : type
387         Parameter description.
388
389     Returns
390     -------
391     dict
392          Colorspaces and transforms converting between those colorspaces and
393          the reference colorspace, *ACES*.
394     """
395
396     print('generateLUTs - begin')
397     config_data = {}
398
399     #
400     # Define the reference color space
401     #
402     ACES = ColorSpace('ACES2065-1')
403     ACES.description = (
404         'The Academy Color Encoding System reference color space')
405     ACES.equality_group = ''
406     ACES.family = 'ACES'
407     ACES.is_data = False
408     ACES.allocation_type = OCIO.Constants.ALLOCATION_LG2
409     ACES.allocation_vars = [-15, 6]
410
411     config_data['referenceColorSpace'] = ACES
412
413     #
414     # Define the displays
415     #
416     config_data['displays'] = {}
417
418     #
419     # Define the other color spaces
420     #
421     config_data['colorSpaces'] = []
422
423     # Matrix converting ACES AP1 primaries to AP0
424     ACES_AP1_to_AP0 = [0.6954522414, 0.1406786965, 0.1638690622,
425                        0.0447945634, 0.8596711185, 0.0955343182,
426                        -0.0055258826, 0.0040252103, 1.0015006723]
427
428     # Matrix converting ACES AP0 primaries to XYZ
429     ACES_AP0_to_XYZ = [0.9525523959, 0.0000000000, 0.0000936786,
430                        0.3439664498, 0.7281660966, -0.0721325464,
431                        0.0000000000, 0.0000000000, 1.0088251844]
432
433     #
434     # ACEScc
435     #
436     def create_ACEScc(name='ACEScc',
437                       min_value=0.0,
438                       max_value=1.0,
439                       input_scale=1.0):
440         cs = ColorSpace(name)
441         cs.description = 'The %s color space' % name
442         cs.equality_group = ''
443         cs.family = 'ACES'
444         cs.is_data = False
445
446         ctls = [
447             '%s/ACEScc/ACEScsc.ACEScc_to_ACES.a1.0.0.ctl' % aces_CTL_directory,
448             # This transform gets back to the AP1 primaries
449             # Useful as the 1d LUT is only covering the transfer function
450             # The primaries switch is covered by the matrix below
451             '%s/ACEScg/ACEScsc.ACES_to_ACEScg.a1.0.0.ctl' % aces_CTL_directory
452         ]
453         lut = '%s_to_ACES.spi1d' % name
454
455         # Remove spaces and parentheses
456         lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
457
458         generate_1d_LUT_from_CTL(
459             lut_directory + '/' + lut,
460             ctls,
461             lut_resolution_1d,
462             'float',
463             input_scale,
464             1.0,
465             {},
466             cleanup,
467             aces_CTL_directory,
468             min_value,
469             max_value)
470
471         cs.to_reference_transforms = []
472         cs.to_reference_transforms.append({
473             'type': 'lutFile',
474             'path': lut,
475             'interpolation': 'linear',
476             'direction': 'forward'
477         })
478
479         # AP1 primaries to AP0 primaries
480         cs.to_reference_transforms.append({
481             'type': 'matrix',
482             'matrix': mat44_from_mat33(ACES_AP1_to_AP0),
483             'direction': 'forward'
484         })
485
486         cs.from_reference_transforms = []
487         return cs
488
489     ACEScc = create_ACEScc()
490     config_data['colorSpaces'].append(ACEScc)
491
492     #
493     # ACESproxy
494     #
495     def create_ACESproxy(name='ACESproxy'):
496         cs = ColorSpace(name)
497         cs.description = 'The %s color space' % name
498         cs.equality_group = ''
499         cs.family = 'ACES'
500         cs.is_data = False
501
502         ctls = [
503             '%s/ACESproxy/ACEScsc.ACESproxy10i_to_ACES.a1.0.0.ctl' % (
504                 aces_CTL_directory),
505             # This transform gets back to the AP1 primaries
506             # Useful as the 1d LUT is only covering the transfer function
507             # The primaries switch is covered by the matrix below
508             '%s/ACEScg/ACEScsc.ACES_to_ACEScg.a1.0.0.ctl' % aces_CTL_directory
509         ]
510         lut = '%s_to_aces.spi1d' % name
511
512         # Remove spaces and parentheses
513         lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
514
515         generate_1d_LUT_from_CTL(
516             lut_directory + '/' + lut,
517             ctls,
518             lut_resolution_1d,
519             'uint16',
520             64.0,
521             1.0,
522             {},
523             cleanup,
524             aces_CTL_directory)
525
526         cs.to_reference_transforms = []
527         cs.to_reference_transforms.append({
528             'type': 'lutFile',
529             'path': lut,
530             'interpolation': 'linear',
531             'direction': 'forward'
532         })
533
534         # AP1 primaries to AP0 primaries
535         cs.to_reference_transforms.append({
536             'type': 'matrix',
537             'matrix': mat44_from_mat33(ACES_AP1_to_AP0),
538             'direction': 'forward'
539         })
540
541         cs.from_reference_transforms = []
542         return cs
543
544     ACESproxy = create_ACESproxy()
545     config_data['colorSpaces'].append(ACESproxy)
546
547     #
548     # ACEScg
549     #
550     def create_ACEScg(name='ACEScg'):
551         cs = ColorSpace(name)
552         cs.description = 'The %s color space' % name
553         cs.equality_group = ''
554         cs.family = 'ACES'
555         cs.is_data = False
556
557         cs.to_reference_transforms = []
558
559         # AP1 primaries to AP0 primaries
560         cs.to_reference_transforms.append({
561             'type': 'matrix',
562             'matrix': mat44_from_mat33(ACES_AP1_to_AP0),
563             'direction': 'forward'
564         })
565
566         cs.from_reference_transforms = []
567         return cs
568
569     ACEScg = create_ACEScg()
570     config_data['colorSpaces'].append(ACEScg)
571
572     #
573     # ADX
574     #
575     def create_ADX(bit_depth=10, name='ADX'):
576         name = '%s%s' % (name, bit_depth)
577         cs = ColorSpace(name)
578         cs.description = '%s color space - used for film scans' % name
579         cs.equality_group = ''
580         cs.family = 'ADX'
581         cs.is_data = False
582
583         if bit_depth == 10:
584             cs.bit_depth = bit_depth = OCIO.Constants.BIT_DEPTH_UINT10
585             adx_to_cdd = [1023.0 / 500.0, 0.0, 0.0, 0.0,
586                           0.0, 1023.0 / 500.0, 0.0, 0.0,
587                           0.0, 0.0, 1023.0 / 500.0, 0.0,
588                           0.0, 0.0, 0.0, 1.0]
589             offset = [-95.0 / 500.0, -95.0 / 500.0, -95.0 / 500.0, 0.0]
590         elif bit_depth == 16:
591             cs.bit_depth = bit_depth = OCIO.Constants.BIT_DEPTH_UINT16
592             adx_to_cdd = [65535.0 / 8000.0, 0.0, 0.0, 0.0,
593                           0.0, 65535.0 / 8000.0, 0.0, 0.0,
594                           0.0, 0.0, 65535.0 / 8000.0, 0.0,
595                           0.0, 0.0, 0.0, 1.0]
596             offset = [-1520.0 / 8000.0, -1520.0 / 8000.0, -1520.0 / 8000.0,
597                       0.0]
598
599         cs.to_reference_transforms = []
600
601         # Convert from ADX to Channel-Dependent Density
602         cs.to_reference_transforms.append({
603             'type': 'matrix',
604             'matrix': adx_to_cdd,
605             'offset': offset,
606             'direction': 'forward'
607         })
608
609         # Convert from Channel-Dependent Density to Channel-Independent Density
610         cs.to_reference_transforms.append({
611             'type': 'matrix',
612             'matrix': [0.75573, 0.22197, 0.02230, 0,
613                        0.05901, 0.96928, -0.02829, 0,
614                        0.16134, 0.07406, 0.76460, 0,
615                        0.0, 0.0, 0.0, 1.0],
616             'direction': 'forward'
617         })
618
619         # Copied from Alex Fry's adx_cid_to_rle.py
620         def create_CID_to_RLE_LUT():
621             def interpolate_1D(x, xp, fp):
622                 return numpy.interp(x, xp, fp)
623
624             LUT_1D_xp = [-0.190000000000000,
625                          0.010000000000000,
626                          0.028000000000000,
627                          0.054000000000000,
628                          0.095000000000000,
629                          0.145000000000000,
630                          0.220000000000000,
631                          0.300000000000000,
632                          0.400000000000000,
633                          0.500000000000000,
634                          0.600000000000000]
635
636             LUT_1D_fp = [-6.000000000000000,
637                          -2.721718645000000,
638                          -2.521718645000000,
639                          -2.321718645000000,
640                          -2.121718645000000,
641                          -1.921718645000000,
642                          -1.721718645000000,
643                          -1.521718645000000,
644                          -1.321718645000000,
645                          -1.121718645000000,
646                          -0.926545676714876]
647
648             REF_PT = ((7120.0 - 1520.0) / 8000.0 * (100.0 / 55.0) -
649                       math.log(0.18, 10.0))
650
651             def cid_to_rle(x):
652                 if x <= 0.6:
653                     return interpolate_1D(x, LUT_1D_xp, LUT_1D_fp)
654                 return (100.0 / 55.0) * x - REF_PT
655
656             def fit(value, from_min, from_max, to_min, to_max):
657                 if from_min == from_max:
658                     raise ValueError('from_min == from_max')
659                 return (value - from_min) / (from_max - from_min) * (
660                     to_max - to_min) + to_min
661
662             NUM_SAMPLES = 2 ** 12
663             RANGE = (-0.19, 3.0)
664             data = []
665             for i in xrange(NUM_SAMPLES):
666                 x = i / (NUM_SAMPLES - 1.0)
667                 x = fit(x, 0.0, 1.0, RANGE[0], RANGE[1])
668                 data.append(cid_to_rle(x))
669
670             lut = 'ADX_CID_to_RLE.spi1d'
671             write_SPI_1d(lut_directory + '/' + lut, RANGE[0], RANGE[1],
672                          data,
673                          NUM_SAMPLES, 1)
674
675             return lut
676
677         # Convert Channel Independent Density values to Relative Log Exposure
678         # values.
679         lut = create_CID_to_RLE_LUT()
680         cs.to_reference_transforms.append({
681             'type': 'lutFile',
682             'path': lut,
683             'interpolation': 'linear',
684             'direction': 'forward'
685         })
686
687         # Convert Relative Log Exposure values to Relative Exposure values
688         cs.to_reference_transforms.append({
689             'type': 'log',
690             'base': 10,
691             'direction': 'inverse'
692         })
693
694         # Convert Relative Exposure values to ACES values
695         cs.to_reference_transforms.append({
696             'type': 'matrix',
697             'matrix': [0.72286, 0.12630, 0.15084, 0,
698                        0.11923, 0.76418, 0.11659, 0,
699                        0.01427, 0.08213, 0.90359, 0,
700                        0.0, 0.0, 0.0, 1.0],
701             'direction': 'forward'
702         })
703
704         cs.from_reference_transforms = []
705         return cs
706
707     ADX10 = create_ADX(bit_depth=10)
708     config_data['colorSpaces'].append(ADX10)
709
710     ADX16 = create_ADX(bit_depth=16)
711     config_data['colorSpaces'].append(ADX16)
712
713     #
714     # Camera Input Transforms
715     #
716
717     # RED color spaces to ACES
718     red_colorspaces = red.create_colorspaces(lut_directory, lut_resolution_1d)
719     for cs in red_colorspaces:
720         config_data['colorSpaces'].append(cs)
721
722     # Canon-Log to ACES
723     canon_colorspaces = canon.create_colorspaces(lut_directory,
724                                                  lut_resolution_1d)
725     for cs in canon_colorspaces:
726         config_data['colorSpaces'].append(cs)
727
728     # S-Log to ACES
729     sony_colorSpaces = sony.create_colorspaces(lut_directory,
730                                                lut_resolution_1d)
731     for cs in sony_colorSpaces:
732         config_data['colorSpaces'].append(cs)
733
734     # Log-C to ACES
735     arri_colorSpaces = arri.create_colorspaces(lut_directory,
736                                                lut_resolution_1d)
737     for cs in arri_colorSpaces:
738         config_data['colorSpaces'].append(cs)
739
740     #
741     # Generic log transform
742     #
743     def create_generic_log(name='log',
744                            min_value=0.0,
745                            max_value=1.0,
746                            input_scale=1.0,
747                            middle_grey=0.18,
748                            min_exposure=-6.0,
749                            max_exposure=6.5,
750                            lut_resolution_1d=lut_resolution_1d):
751         cs = ColorSpace(name)
752         cs.description = 'The %s color space' % name
753         cs.equality_group = name
754         cs.family = 'Utility'
755         cs.is_data = False
756
757         ctls = [
758             '%s/utilities/ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl' % (
759                 aces_CTL_directory)]
760         lut = '%s_to_aces.spi1d' % name
761
762         # Remove spaces and parentheses
763         lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
764
765         generate_1d_LUT_from_CTL(
766             lut_directory + '/' + lut,
767             ctls,
768             lut_resolution_1d,
769             'float',
770             input_scale,
771             1.0,
772             {
773                 'middleGrey': middle_grey,
774                 'minExposure': min_exposure,
775                 'maxExposure': max_exposure
776             },
777             cleanup,
778             aces_CTL_directory,
779             min_value,
780             max_value)
781
782         cs.to_reference_transforms = []
783         cs.to_reference_transforms.append({
784             'type': 'lutFile',
785             'path': lut,
786             'interpolation': 'linear',
787             'direction': 'forward'
788         })
789
790         cs.from_reference_transforms = []
791         return cs
792
793     #
794     # ACES LMTs
795     #
796     def create_ACES_LMT(lmt_name,
797                         lmt_values,
798                         shaper_info,
799                         lut_resolution_1d=1024,
800                         lut_resolution_3d=64,
801                         cleanup=True):
802         cs = ColorSpace('%s' % lmt_name)
803         cs.description = 'The ACES Look Transform: %s' % lmt_name
804         cs.equality_group = ''
805         cs.family = 'Look'
806         cs.is_data = False
807
808         pprint.pprint(lmt_values)
809
810         #
811         # Generate the shaper transform
812         #
813         (shaper_name,
814          shaper_to_ACES_CTL,
815          shaper_from_ACES_CTL,
816          shaper_input_scale,
817          shaper_params) = shaper_info
818
819         shaper_lut = '%s_to_aces.spi1d' % shaper_name
820         if (not os.path.exists(lut_directory + '/' + shaper_lut)):
821             ctls = [shaper_to_ACES_CTL % aces_CTL_directory]
822
823             # Remove spaces and parentheses
824             shaper_lut = shaper_lut.replace(
825                 ' ', '_').replace(')', '_').replace('(', '_')
826
827             generate_1d_LUT_from_CTL(
828                 lut_directory + '/' + shaper_lut,
829                 ctls,
830                 lut_resolution_1d,
831                 'float',
832                 1.0 / shaper_input_scale,
833                 1.0,
834                 shaper_params,
835                 cleanup,
836                 aces_CTL_directory)
837
838         shaper_OCIO_transform = {
839             'type': 'lutFile',
840             'path': shaper_lut,
841             'interpolation': 'linear',
842             'direction': 'inverse'
843         }
844
845         #
846         # Generate the forward transform
847         #
848         cs.from_reference_transforms = []
849
850         if 'transformCTL' in lmt_values:
851             ctls = [
852                 shaper_to_ACES_CTL % aces_CTL_directory,
853                 '%s/%s' % (aces_CTL_directory, lmt_values['transformCTL'])
854             ]
855             lut = '%s.%s.spi3d' % (shaper_name, lmt_name)
856
857             # Remove spaces and parentheses
858             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
859
860             generate_3d_LUT_from_CTL(
861                 lut_directory + '/' + lut,
862                 ctls,
863                 lut_resolution_3d,
864                 'float',
865                 1.0 / shaper_input_scale,
866                 1.0,
867                 shaper_params,
868                 cleanup,
869                 aces_CTL_directory)
870
871             cs.from_reference_transforms.append(shaper_OCIO_transform)
872             cs.from_reference_transforms.append({
873                 'type': 'lutFile',
874                 'path': lut,
875                 'interpolation': 'tetrahedral',
876                 'direction': 'forward'
877             })
878
879         #
880         # Generate the inverse transform
881         #
882         cs.to_reference_transforms = []
883
884         if 'transformCTLInverse' in lmt_values:
885             ctls = [
886                 '%s/%s' % (
887                     aces_CTL_directory, odt_values['transformCTLInverse']),
888                 shaper_from_ACES_CTL % aces_CTL_directory
889             ]
890             lut = 'Inverse.%s.%s.spi3d' % (odt_name, shaper_name)
891
892             # Remove spaces and parentheses
893             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
894
895             generate_3d_LUT_from_CTL(
896                 lut_directory + '/' + lut,
897                 ctls,
898                 lut_resolution_3d,
899                 'half',
900                 1.0,
901                 shaper_input_scale,
902                 shaper_params,
903                 cleanup,
904                 aces_CTL_directory)
905
906             cs.to_reference_transforms.append({
907                 'type': 'lutFile',
908                 'path': lut,
909                 'interpolation': 'tetrahedral',
910                 'direction': 'forward'
911             })
912
913             shaper_inverse = shaper_OCIO_transform.copy()
914             shaper_inverse['direction'] = 'forward'
915             cs.to_reference_transforms.append(shaper_inverse)
916
917         return cs
918
919     #
920     # LMT Shaper
921     #
922
923     lmt_lut_resolution_1d = max(4096, lut_resolution_1d)
924     lmt_lut_resolution_3d = max(65, lut_resolution_3d)
925
926     # Log 2 shaper
927     lmt_shaper_name = 'LMT Shaper'
928     lmt_params = {
929         'middleGrey': 0.18,
930         'minExposure': -10.0,
931         'maxExposure': 6.5
932     }
933     lmt_shaper = create_generic_log(name=lmt_shaper_name,
934                                     middle_grey=lmt_params['middleGrey'],
935                                     min_exposure=lmt_params['minExposure'],
936                                     max_exposure=lmt_params['maxExposure'],
937                                     lut_resolution_1d=lmt_lut_resolution_1d)
938     config_data['colorSpaces'].append(lmt_shaper)
939
940     shaper_input_scale_generic_log2 = 1.0
941
942     # Log 2 shaper name and CTL transforms bundled up
943     lmt_shaper_data = [
944         lmt_shaper_name,
945         '%s/utilities/ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl',
946         '%s/utilities/ACESlib.OCIO_shaper_lin_to_log2_param.a1.0.0.ctl',
947         shaper_input_scale_generic_log2,
948         lmt_params
949     ]
950
951     sorted_LMTs = sorted(lmt_info.iteritems(), key=lambda x: x[1])
952     print(sorted_LMTs)
953     for lmt in sorted_LMTs:
954         (lmt_name, lmt_values) = lmt
955         cs = create_ACES_LMT(
956             lmt_values['transformUserName'],
957             lmt_values,
958             lmt_shaper_data,
959             lmt_lut_resolution_1d,
960             lmt_lut_resolution_3d,
961             cleanup)
962         config_data['colorSpaces'].append(cs)
963
964     #
965     # ACES RRT with the supplied ODT
966     #
967     def create_ACES_RRT_plus_ODT(odt_name,
968                                  odt_values,
969                                  shaper_info,
970                                  lut_resolution_1d=1024,
971                                  lut_resolution_3d=64,
972                                  cleanup=True):
973         cs = ColorSpace('%s' % odt_name)
974         cs.description = '%s - %s Output Transform' % (
975             odt_values['transformUserNamePrefix'], odt_name)
976         cs.equality_group = ''
977         cs.family = 'Output'
978         cs.is_data = False
979
980         pprint.pprint(odt_values)
981
982         #
983         # Generate the shaper transform
984         #
985         # if 'shaperCTL' in odtValues:
986         (shaper_name,
987          shaper_to_ACES_CTL,
988          shaper_from_ACES_CTL,
989          shaper_input_scale,
990          shaper_params) = shaper_info
991
992         if 'legalRange' in odt_values:
993             shaper_params['legalRange'] = odt_values['legalRange']
994         else:
995             shaper_params['legalRange'] = 0
996
997         shaper_lut = '%s_to_aces.spi1d' % shaper_name
998         if (not os.path.exists(lut_directory + '/' + shaper_lut)):
999             ctls = [shaper_to_ACES_CTL % aces_CTL_directory]
1000
1001             # Remove spaces and parentheses
1002             shaper_lut = shaper_lut.replace(
1003                 ' ', '_').replace(')', '_').replace('(', '_')
1004
1005             generate_1d_LUT_from_CTL(
1006                 lut_directory + '/' + shaper_lut,
1007                 ctls,
1008                 lut_resolution_1d,
1009                 'float',
1010                 1.0 / shaper_input_scale,
1011                 1.0,
1012                 shaper_params,
1013                 cleanup,
1014                 aces_CTL_directory)
1015
1016         shaper_OCIO_transform = {
1017             'type': 'lutFile',
1018             'path': shaper_lut,
1019             'interpolation': 'linear',
1020             'direction': 'inverse'
1021         }
1022
1023         #
1024         # Generate the forward transform
1025         #
1026         cs.from_reference_transforms = []
1027
1028         if 'transformLUT' in odt_values:
1029             # Copy into the lut dir
1030             transform_LUT_file_name = os.path.basename(
1031                 odt_values['transformLUT'])
1032             lut = lut_directory + '/' + transform_LUT_file_name
1033             shutil.copy(odt_values['transformLUT'], lut)
1034
1035             cs.from_reference_transforms.append(shaper_OCIO_transform)
1036             cs.from_reference_transforms.append({
1037                 'type': 'lutFile',
1038                 'path': transform_LUT_file_name,
1039                 'interpolation': 'tetrahedral',
1040                 'direction': 'forward'
1041             })
1042         elif 'transformCTL' in odt_values:
1043             # shaperLut
1044
1045             ctls = [
1046                 shaper_to_ACES_CTL % aces_CTL_directory,
1047                 '%s/rrt/RRT.a1.0.0.ctl' % aces_CTL_directory,
1048                 '%s/odt/%s' % (aces_CTL_directory, odt_values['transformCTL'])
1049             ]
1050             lut = '%s.RRT.a1.0.0.%s.spi3d' % (shaper_name, odt_name)
1051
1052             # Remove spaces and parentheses
1053             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
1054
1055             generate_3d_LUT_from_CTL(lut_directory + '/' + lut,
1056                                      # shaperLUT,
1057                                      ctls,
1058                                      lut_resolution_3d,
1059                                      'float',
1060                                      1.0 / shaper_input_scale,
1061                                      1.0,
1062                                      shaper_params,
1063                                      cleanup,
1064                                      aces_CTL_directory)
1065
1066             cs.from_reference_transforms.append(shaper_OCIO_transform)
1067             cs.from_reference_transforms.append({
1068                 'type': 'lutFile',
1069                 'path': lut,
1070                 'interpolation': 'tetrahedral',
1071                 'direction': 'forward'
1072             })
1073
1074         #
1075         # Generate the inverse transform
1076         #
1077         cs.to_reference_transforms = []
1078
1079         if 'transformLUTInverse' in odt_values:
1080             # Copy into the lut dir
1081             transform_LUT_inverse_file_name = os.path.basename(
1082                 odt_values['transformLUTInverse'])
1083             lut = lut_directory + '/' + transform_LUT_inverse_file_name
1084             shutil.copy(odt_values['transformLUTInverse'], lut)
1085
1086             cs.to_reference_transforms.append({
1087                 'type': 'lutFile',
1088                 'path': transform_LUT_inverse_file_name,
1089                 'interpolation': 'tetrahedral',
1090                 'direction': 'forward'
1091             })
1092
1093             shaper_inverse = shaper_OCIO_transform.copy()
1094             shaper_inverse['direction'] = 'forward'
1095             cs.to_reference_transforms.append(shaper_inverse)
1096         elif 'transformCTLInverse' in odt_values:
1097             ctls = [
1098                 '%s/odt/%s' % (
1099                     aces_CTL_directory, odt_values['transformCTLInverse']),
1100                 '%s/rrt/InvRRT.a1.0.0.ctl' % aces_CTL_directory,
1101                 shaper_from_ACES_CTL % aces_CTL_directory
1102             ]
1103             lut = 'InvRRT.a1.0.0.%s.%s.spi3d' % (odt_name, shaper_name)
1104
1105             # Remove spaces and parentheses
1106             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
1107
1108             generate_3d_LUT_from_CTL(
1109                 lut_directory + '/' + lut,
1110                 # None,
1111                 ctls,
1112                 lut_resolution_3d,
1113                 'half',
1114                 1.0,
1115                 shaper_input_scale,
1116                 shaper_params,
1117                 cleanup,
1118                 aces_CTL_directory)
1119
1120             cs.to_reference_transforms.append({
1121                 'type': 'lutFile',
1122                 'path': lut,
1123                 'interpolation': 'tetrahedral',
1124                 'direction': 'forward'
1125             })
1126
1127             shaper_inverse = shaper_OCIO_transform.copy()
1128             shaper_inverse['direction'] = 'forward'
1129             cs.to_reference_transforms.append(shaper_inverse)
1130
1131         return cs
1132
1133     #
1134     # RRT/ODT shaper options
1135     #
1136     shaper_data = {}
1137
1138     # Log 2 shaper
1139     log2_shaper_name = shaper_name
1140     log2_params = {
1141         'middleGrey': 0.18,
1142         'minExposure': -6.0,
1143         'maxExposure': 6.5
1144     }
1145     log2_shaper = create_generic_log(
1146         name=log2_shaper_name,
1147         middle_grey=log2_params['middleGrey'],
1148         min_exposure=log2_params['minExposure'],
1149         max_exposure=log2_params['maxExposure'])
1150     config_data['colorSpaces'].append(log2_shaper)
1151
1152     shaper_input_scale_generic_log2 = 1.0
1153
1154     # Log 2 shaper name and CTL transforms bundled up
1155     log2_shaper_data = [
1156         log2_shaper_name,
1157         '%s/utilities/ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl',
1158         '%s/utilities/ACESlib.OCIO_shaper_lin_to_log2_param.a1.0.0.ctl',
1159         shaper_input_scale_generic_log2,
1160         log2_params
1161     ]
1162
1163     shaper_data[log2_shaper_name] = log2_shaper_data
1164
1165     #
1166     # Shaper that also includes the AP1 primaries
1167     # - Needed for some LUT baking steps
1168     #
1169     log2_shaper_AP1 = create_generic_log(
1170         name=log2_shaper_name,
1171         middle_grey=log2_params['middleGrey'],
1172         min_exposure=log2_params['minExposure'],
1173         max_exposure=log2_params['maxExposure'])
1174     log2_shaper_AP1.name = '%s - AP1' % log2_shaper_AP1.name
1175     # AP1 primaries to AP0 primaries
1176     log2_shaper_AP1.to_reference_transforms.append({
1177         'type': 'matrix',
1178         'matrix': mat44_from_mat33(ACES_AP1_to_AP0),
1179         'direction': 'forward'
1180     })
1181     config_data['colorSpaces'].append(log2_shaper_AP1)
1182
1183     #
1184     # Choose your shaper
1185     #
1186     rrt_shaper_name = log2_shaper_name
1187     rrt_shaper = log2_shaper_data
1188
1189     #
1190     # RRT + ODT Combinations
1191     #
1192     sorted_odts = sorted(odt_info.iteritems(), key=lambda x: x[1])
1193     print(sorted_odts)
1194     for odt in sorted_odts:
1195         (odt_name, odt_values) = odt
1196
1197         # Have to handle ODTs that can generate either legal or full output
1198         if odt_name in ['Academy.Rec2020_100nits_dim.a1.0.0',
1199                         'Academy.Rec709_100nits_dim.a1.0.0',
1200                         'Academy.Rec709_D60sim_100nits_dim.a1.0.0']:
1201             odt_name_legal = '%s - Legal' % odt_values['transformUserName']
1202         else:
1203             odt_name_legal = odt_values['transformUserName']
1204
1205         odt_legal = odt_values.copy()
1206         odt_legal['legalRange'] = 1
1207
1208         cs = create_ACES_RRT_plus_ODT(
1209             odt_name_legal,
1210             odt_legal,
1211             rrt_shaper,
1212             lut_resolution_1d,
1213             lut_resolution_3d,
1214             cleanup)
1215         config_data['colorSpaces'].append(cs)
1216
1217         # Create a display entry using this color space
1218         config_data['displays'][odt_name_legal] = {
1219             'Linear': ACES,
1220             'Log': ACEScc,
1221             'Output Transform': cs}
1222
1223         if odt_name in ['Academy.Rec2020_100nits_dim.a1.0.0',
1224                         'Academy.Rec709_100nits_dim.a1.0.0',
1225                         'Academy.Rec709_D60sim_100nits_dim.a1.0.0']:
1226             print('Generating full range ODT for %s' % odt_name)
1227
1228             odt_name_full = '%s - Full' % odt_values['transformUserName']
1229             odt_full = odt_values.copy()
1230             odt_full['legalRange'] = 0
1231
1232             cs_full = create_ACES_RRT_plus_ODT(
1233                 odt_name_full,
1234                 odt_full,
1235                 rrt_shaper,
1236                 lut_resolution_1d,
1237                 lut_resolution_3d,
1238                 cleanup)
1239             config_data['colorSpaces'].append(cs_full)
1240
1241             # Create a display entry using this color space
1242             config_data['displays'][odt_name_full] = {
1243                 'Linear': ACES,
1244                 'Log': ACEScc,
1245                 'Output Transform': cs_full}
1246
1247     #
1248     # Generic Matrix transform
1249     #
1250     def create_generic_matrix(name='matrix',
1251                               from_reference_values=[],
1252                               to_reference_values=[]):
1253         cs = ColorSpace(name)
1254         cs.description = 'The %s color space' % name
1255         cs.equality_group = name
1256         cs.family = 'Utility'
1257         cs.is_data = False
1258
1259         cs.to_reference_transforms = []
1260         if to_reference_values != []:
1261             for matrix in to_reference_values:
1262                 cs.to_reference_transforms.append({
1263                     'type': 'matrix',
1264                     'matrix': mat44_from_mat33(matrix),
1265                     'direction': 'forward'
1266                 })
1267
1268         cs.from_reference_transforms = []
1269         if from_reference_values != []:
1270             for matrix in from_reference_values:
1271                 cs.from_reference_transforms.append({
1272                     'type': 'matrix',
1273                     'matrix': mat44_from_mat33(matrix),
1274                     'direction': 'forward'
1275                 })
1276
1277         return cs
1278
1279     cs = create_generic_matrix('XYZ', from_reference_values=[ACES_AP0_to_XYZ])
1280     config_data['colorSpaces'].append(cs)
1281
1282     cs = create_generic_matrix(
1283         'Linear - AP1', to_reference_values=[ACES_AP1_to_AP0])
1284     config_data['colorSpaces'].append(cs)
1285
1286     # ACES to Linear, P3D60 primaries
1287     XYZ_to_P3D60 = [2.4027414142, -0.8974841639, -0.3880533700,
1288                     -0.8325796487, 1.7692317536, 0.0237127115,
1289                     0.0388233815, -0.0824996856, 1.0363685997]
1290
1291     cs = create_generic_matrix(
1292         'Linear - P3-D60',
1293         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_P3D60])
1294     config_data['colorSpaces'].append(cs)
1295
1296     # ACES to Linear, P3D60 primaries
1297     XYZ_to_P3DCI = [2.7253940305, -1.0180030062, -0.4401631952,
1298                     -0.7951680258, 1.6897320548, 0.0226471906,
1299                     0.0412418914, -0.0876390192, 1.1009293786]
1300
1301     cs = create_generic_matrix(
1302         'Linear - P3-DCI',
1303         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_P3DCI])
1304     config_data['colorSpaces'].append(cs)
1305
1306     # ACES to Linear, Rec 709 primaries
1307     XYZ_to_Rec709 = [3.2409699419, -1.5373831776, -0.4986107603,
1308                      -0.9692436363, 1.8759675015, 0.0415550574,
1309                      0.0556300797, -0.2039769589, 1.0569715142]
1310
1311     cs = create_generic_matrix(
1312         'Linear - Rec.709',
1313         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_Rec709])
1314     config_data['colorSpaces'].append(cs)
1315
1316     # ACES to Linear, Rec 2020 primaries
1317     XYZ_to_Rec2020 = [1.7166511880, -0.3556707838, -0.2533662814,
1318                       -0.6666843518, 1.6164812366, 0.0157685458,
1319                       0.0176398574, -0.0427706133, 0.9421031212]
1320
1321     cs = create_generic_matrix(
1322         'Linear - Rec.2020',
1323         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_Rec2020])
1324     config_data['colorSpaces'].append(cs)
1325
1326     print('generateLUTs - end')
1327     return config_data
1328
1329
1330 def generate_baked_LUTs(odt_info,
1331                         shaper_name,
1332                         baked_directory,
1333                         config_path,
1334                         lut_resolution_1d,
1335                         lut_resolution_3d,
1336                         lut_resolution_shaper=1024):
1337     """
1338     Object description.
1339
1340     Parameters
1341     ----------
1342     parameter : type
1343         Parameter description.
1344
1345     Returns
1346     -------
1347     type
1348          Return value description.
1349     """
1350
1351     # Add the legal and full variations into this list
1352     odt_info_C = dict(odt_info)
1353     for odt_CTL_name, odt_values in odt_info.iteritems():
1354         if odt_CTL_name in ['Academy.Rec2020_100nits_dim.a1.0.0',
1355                             'Academy.Rec709_100nits_dim.a1.0.0',
1356                             'Academy.Rec709_D60sim_100nits_dim.a1.0.0']:
1357             odt_name = odt_values['transformUserName']
1358
1359             odt_values_legal = dict(odt_values)
1360             odt_values_legal['transformUserName'] = '%s - Legal' % odt_name
1361             odt_info_C['%s - Legal' % odt_CTL_name] = odt_values_legal
1362
1363             odt_values_full = dict(odt_values)
1364             odt_values_full['transformUserName'] = '%s - Full' % odt_name
1365             odt_info_C['%s - Full' % odt_CTL_name] = odt_values_full
1366
1367             del (odt_info_C[odt_CTL_name])
1368
1369     for odt_CTL_name, odt_values in odt_info_C.iteritems():
1370         odt_prefix = odt_values['transformUserNamePrefix']
1371         odt_name = odt_values['transformUserName']
1372
1373         # For Photoshop
1374         for input_space in ['ACEScc', 'ACESproxy']:
1375             args = ['--iconfig', config_path,
1376                     '-v',
1377                     '--inputspace', input_space]
1378             args += ['--outputspace', '%s' % odt_name]
1379             args += ['--description',
1380                      '%s - %s for %s data' % (odt_prefix,
1381                                               odt_name,
1382                                               input_space)]
1383             args += ['--shaperspace', shaper_name,
1384                      '--shapersize', str(lut_resolution_shaper)]
1385             args += ['--cubesize', str(lut_resolution_3d)]
1386             args += ['--format',
1387                      'icc',
1388                      '%s/photoshop/%s for %s.icc' % (baked_directory,
1389                                                      odt_name,
1390                                                      input_space)]
1391
1392             bake_LUT = Process(description='bake a LUT',
1393                                cmd='ociobakelut',
1394                                args=args)
1395             bake_LUT.execute()
1396
1397         # For Flame, Lustre
1398         for input_space in ['ACEScc', 'ACESproxy']:
1399             args = ['--iconfig', config_path,
1400                     '-v',
1401                     '--inputspace', input_space]
1402             args += ['--outputspace', '%s' % odt_name]
1403             args += ['--description',
1404                      '%s - %s for %s data' % (
1405                          odt_prefix, odt_name, input_space)]
1406             args += ['--shaperspace', shaper_name,
1407                      '--shapersize', str(lut_resolution_shaper)]
1408             args += ['--cubesize', str(lut_resolution_3d)]
1409
1410             fargs = ['--format', 'flame', '%s/flame/%s for %s Flame.3dl' % (
1411                 baked_directory, odt_name, input_space)]
1412             bake_LUT = Process(description='bake a LUT',
1413                                cmd='ociobakelut',
1414                                args=(args + fargs))
1415             bake_LUT.execute()
1416
1417             largs = ['--format', 'lustre', '%s/lustre/%s for %s Lustre.3dl' % (
1418                 baked_directory, odt_name, input_space)]
1419             bake_LUT = Process(description='bake a LUT',
1420                                cmd='ociobakelut',
1421                                args=(args + largs))
1422             bake_LUT.execute()
1423
1424         # For Maya, Houdini
1425         for input_space in ['ACEScg', 'ACES2065-1']:
1426             args = ['--iconfig', config_path,
1427                     '-v',
1428                     '--inputspace', input_space]
1429             args += ['--outputspace', '%s' % odt_name]
1430             args += ['--description',
1431                      '%s - %s for %s data' % (
1432                          odt_prefix, odt_name, input_space)]
1433             if input_space == 'ACEScg':
1434                 lin_shaper_name = '%s - AP1' % shaper_name
1435             else:
1436                 lin_shaper_name = shaper_name
1437             args += ['--shaperspace', lin_shaper_name,
1438                      '--shapersize', str(lut_resolution_shaper)]
1439
1440             args += ['--cubesize', str(lut_resolution_3d)]
1441
1442             margs = ['--format', 'cinespace', '%s/maya/%s for %s Maya.csp' % (
1443                 baked_directory, odt_name, input_space)]
1444             bake_LUT = Process(description='bake a LUT',
1445                                cmd='ociobakelut',
1446                                args=(args + margs))
1447             bake_LUT.execute()
1448
1449             hargs = ['--format', 'houdini',
1450                      '%s/houdini/%s for %s Houdini.lut' % (
1451                          baked_directory, odt_name, input_space)]
1452             bake_LUT = Process(description='bake a LUT',
1453                                cmd='ociobakelut',
1454                                args=(args + hargs))
1455             bake_LUT.execute()
1456
1457
1458 def create_config_dir(config_directory, bake_secondary_LUTs):
1459     """
1460     Object description.
1461
1462     Parameters
1463     ----------
1464     parameter : type
1465         Parameter description.
1466
1467     Returns
1468     -------
1469     type
1470          Return value description.
1471     """
1472
1473     dirs = [config_directory, '%s/luts' % config_directory]
1474     if bake_secondary_LUTs:
1475         dirs.extend(['%s/baked' % config_directory,
1476                      '%s/baked/flame' % config_directory,
1477                      '%s/baked/photoshop' % config_directory,
1478                      '%s/baked/houdini' % config_directory,
1479                      '%s/baked/lustre' % config_directory,
1480                      '%s/baked/maya' % config_directory])
1481
1482     for d in dirs:
1483         not os.path.exists(d) and os.mkdir(d)
1484
1485
1486 def get_transform_info(ctl_transform):
1487     """
1488     Object description.
1489
1490     Parameters
1491     ----------
1492     parameter : type
1493         Parameter description.
1494
1495     Returns
1496     -------
1497     type
1498          Return value description.
1499     """
1500
1501     # TODO: Use *with* statement.
1502     fp = open(ctl_transform, 'rb')
1503
1504     # Read lines
1505     lines = fp.readlines()
1506
1507     # Grab transform ID and User Name
1508     transform_ID = lines[1][3:].split('<')[1].split('>')[1].strip()
1509     # print(transformID)
1510     transform_user_name = '-'.join(
1511         lines[2][3:].split('<')[1].split('>')[1].split('-')[1:]).strip()
1512     transform_user_name_prefix = (
1513         lines[2][3:].split('<')[1].split('>')[1].split('-')[0].strip())
1514     # print(transformUserName)
1515     fp.close()
1516
1517     return transform_ID, transform_user_name, transform_user_name_prefix
1518
1519
1520 def get_ODT_info(aces_CTL_directory):
1521     """
1522     Object description.
1523
1524     For versions after WGR9.
1525
1526     Parameters
1527     ----------
1528     parameter : type
1529         Parameter description.
1530
1531     Returns
1532     -------
1533     type
1534          Return value description.
1535     """
1536
1537     # TODO: Investigate usage of *files_walker* definition here.
1538     # Credit to Alex Fry for the original approach here
1539     odt_dir = os.path.join(aces_CTL_directory, 'odt')
1540     all_odt = []
1541     for dir_name, subdir_list, file_list in os.walk(odt_dir):
1542         for fname in file_list:
1543             all_odt.append((os.path.join(dir_name, fname)))
1544
1545     odt_CTLs = [x for x in all_odt if
1546                 ('InvODT' not in x) and (os.path.split(x)[-1][0] != '.')]
1547
1548     # print odtCTLs
1549
1550     odts = {}
1551
1552     for odt_CTL in odt_CTLs:
1553         odt_tokens = os.path.split(odt_CTL)
1554         # print(odtTokens)
1555
1556         # Handle nested directories
1557         odt_path_tokens = os.path.split(odt_tokens[-2])
1558         odt_dir = odt_path_tokens[-1]
1559         while odt_path_tokens[-2][-3:] != 'odt':
1560             odt_path_tokens = os.path.split(odt_path_tokens[-2])
1561             odt_dir = os.path.join(odt_path_tokens[-1], odt_dir)
1562
1563         # Build full name
1564         # print('odtDir : %s' % odtDir)
1565         transform_CTL = odt_tokens[-1]
1566         # print(transformCTL)
1567         odt_name = string.join(transform_CTL.split('.')[1:-1], '.')
1568         # print(odtName)
1569
1570         # Find id, user name and user name prefix
1571         (transform_ID,
1572          transform_user_name,
1573          transform_user_name_prefix) = get_transform_info(
1574             '%s/odt/%s/%s' % (aces_CTL_directory, odt_dir, transform_CTL))
1575
1576         # Find inverse
1577         transform_CTL_inverse = 'InvODT.%s.ctl' % odt_name
1578         if not os.path.exists(
1579                 os.path.join(odt_tokens[-2], transform_CTL_inverse)):
1580             transform_CTL_inverse = None
1581         # print(transformCTLInverse)
1582
1583         # Add to list of ODTs
1584         odts[odt_name] = {}
1585         odts[odt_name]['transformCTL'] = os.path.join(odt_dir, transform_CTL)
1586         if transform_CTL_inverse != None:
1587             odts[odt_name]['transformCTLInverse'] = os.path.join(
1588                 odt_dir, transform_CTL_inverse)
1589
1590         odts[odt_name]['transformID'] = transform_ID
1591         odts[odt_name]['transformUserNamePrefix'] = transform_user_name_prefix
1592         odts[odt_name]['transformUserName'] = transform_user_name
1593
1594         print('ODT : %s' % odt_name)
1595         print('\tTransform ID               : %s' % transform_ID)
1596         print('\tTransform User Name Prefix : %s' % transform_user_name_prefix)
1597         print('\tTransform User Name        : %s' % transform_user_name)
1598         print('\tForward ctl                : %s' % (
1599             odts[odt_name]['transformCTL']))
1600         if 'transformCTLInverse' in odts[odt_name]:
1601             print('\tInverse ctl                : %s' % (
1602                 odts[odt_name]['transformCTLInverse']))
1603         else:
1604             print('\tInverse ctl                : %s' % 'None')
1605
1606     print('\n')
1607
1608     return odts
1609
1610
1611 def get_LMT_info(aces_CTL_directory):
1612     """
1613     Object description.
1614
1615     For versions after WGR9.
1616
1617     Parameters
1618     ----------
1619     parameter : type
1620         Parameter description.
1621
1622     Returns
1623     -------
1624     type
1625          Return value description.
1626     """
1627
1628     # TODO: Investigate refactoring with previous definition.
1629
1630     # Credit to Alex Fry for the original approach here
1631     lmt_dir = os.path.join(aces_CTL_directory, 'lmt')
1632     all_lmt = []
1633     for dir_name, subdir_list, file_list in os.walk(lmt_dir):
1634         for fname in file_list:
1635             all_lmt.append((os.path.join(dir_name, fname)))
1636
1637     lmt_CTLs = [x for x in all_lmt if
1638                 ('InvLMT' not in x) and ('README' not in x) and (
1639                     os.path.split(x)[-1][0] != '.')]
1640
1641     # print lmtCTLs
1642
1643     lmts = {}
1644
1645     for lmt_CTL in lmt_CTLs:
1646         lmt_tokens = os.path.split(lmt_CTL)
1647         # print(lmtTokens)
1648
1649         # Handle nested directories
1650         lmt_path_tokens = os.path.split(lmt_tokens[-2])
1651         lmt_dir = lmt_path_tokens[-1]
1652         while lmt_path_tokens[-2][-3:] != 'ctl':
1653             lmt_path_tokens = os.path.split(lmt_path_tokens[-2])
1654             lmt_dir = os.path.join(lmt_path_tokens[-1], lmt_dir)
1655
1656         # Build full name
1657         # print('lmtDir : %s' % lmtDir)
1658         transform_CTL = lmt_tokens[-1]
1659         # print(transformCTL)
1660         lmt_name = string.join(transform_CTL.split('.')[1:-1], '.')
1661         # print(lmtName)
1662
1663         # Find id, user name and user name prefix
1664         (transform_ID,
1665          transform_user_name,
1666          transform_user_name_prefix) = get_transform_info(
1667             '%s/%s/%s' % (aces_CTL_directory, lmt_dir, transform_CTL))
1668
1669         # Find inverse
1670         transform_CTL_inverse = 'InvLMT.%s.ctl' % lmt_name
1671         if not os.path.exists(
1672                 os.path.join(lmt_tokens[-2], transform_CTL_inverse)):
1673             transform_CTL_inverse = None
1674         # print(transformCTLInverse)
1675
1676         # Add to list of LMTs
1677         lmts[lmt_name] = {}
1678         lmts[lmt_name]['transformCTL'] = os.path.join(lmt_dir, transform_CTL)
1679         if transform_CTL_inverse != None:
1680             # TODO: Check unresolved *odt_name* referemce.
1681             lmts[odt_name]['transformCTLInverse'] = os.path.join(
1682                 lmt_dir, transform_CTL_inverse)
1683
1684         lmts[lmt_name]['transformID'] = transform_ID
1685         lmts[lmt_name]['transformUserNamePrefix'] = transform_user_name_prefix
1686         lmts[lmt_name]['transformUserName'] = transform_user_name
1687
1688         print('LMT : %s' % lmt_name)
1689         print('\tTransform ID               : %s' % transform_ID)
1690         print('\tTransform User Name Prefix : %s' % transform_user_name_prefix)
1691         print('\tTransform User Name        : %s' % transform_user_name)
1692         print('\t Forward ctl : %s' % lmts[lmt_name]['transformCTL'])
1693         if 'transformCTLInverse' in lmts[lmt_name]:
1694             print('\t Inverse ctl : %s' % (
1695                 lmts[lmt_name]['transformCTLInverse']))
1696         else:
1697             print('\t Inverse ctl : %s' % 'None')
1698
1699     print('\n')
1700
1701     return lmts
1702
1703
1704 def create_ACES_config(aces_CTL_directory,
1705                        config_directory,
1706                        lut_resolution_1d=4096,
1707                        lut_resolution_3d=64,
1708                        bake_secondary_LUTs=True,
1709                        cleanup=True):
1710     """
1711     Creates the ACES configuration.
1712
1713     Parameters
1714     ----------
1715     parameter : type
1716         Parameter description.
1717
1718     Returns
1719     -------
1720     type
1721          Return value description.
1722     """
1723
1724     # Get ODT names and CTL paths
1725     odt_info = get_ODT_info(aces_CTL_directory)
1726
1727     # Get ODT names and CTL paths
1728     lmt_info = get_LMT_info(aces_CTL_directory)
1729
1730     # Create config dir
1731     create_config_dir(config_directory, bake_secondary_LUTs)
1732
1733     # Generate config data and LUTs for different transforms
1734     lut_directory = '%s/luts' % config_directory
1735     shaper_name = 'Output Shaper'
1736     config_data = generate_LUTs(odt_info,
1737                                 lmt_info,
1738                                 shaper_name,
1739                                 aces_CTL_directory,
1740                                 lut_directory,
1741                                 lut_resolution_1d,
1742                                 lut_resolution_3d,
1743                                 cleanup)
1744
1745     # Create the config using the generated LUTs
1746     print('Creating generic config')
1747     config = create_config(config_data)
1748     print('\n\n\n')
1749
1750     # Write the config to disk
1751     write_config(config, '%s/config.ocio' % config_directory)
1752
1753     # Create a config that will work well with Nuke using the previously
1754     # generated LUTs.
1755     print('Creating Nuke-specific config')
1756     nuke_config = create_config(config_data, nuke=True)
1757     print('\n\n\n')
1758
1759     # Write the config to disk
1760     write_config(nuke_config, '%s/nuke_config.ocio' % config_directory)
1761
1762     # Bake secondary LUTs using the config
1763     if bake_secondary_LUTs:
1764         generate_baked_LUTs(odt_info,
1765                             shaper_name,
1766                             '%s/baked' % config_directory,
1767                             '%s/config.ocio' % config_directory,
1768                             lut_resolution_1d,
1769                             lut_resolution_3d,
1770                             lut_resolution_1d)
1771
1772     return True
1773
1774
1775 def main():
1776     """
1777     Object description.
1778
1779     Parameters
1780     ----------
1781     parameter : type
1782         Parameter description.
1783
1784     Returns
1785     -------
1786     type
1787          Return value description.
1788     """
1789
1790     import optparse
1791
1792     p = optparse.OptionParser(description='An OCIO config generation script',
1793                               prog='createACESConfig',
1794                               version='createACESConfig 0.1',
1795                               usage='%prog [options]')
1796     p.add_option('--acesCTLDir', '-a', default=os.environ.get(
1797         'ACES_OCIO_CTL_DIRECTORY', None))
1798     p.add_option('--configDir', '-c', default=os.environ.get(
1799         'ACES_OCIO_CONFIGURATION_DIRECTORY', None))
1800     p.add_option('--lutResolution1d', default=4096)
1801     p.add_option('--lutResolution3d', default=64)
1802     p.add_option('--dontBakeSecondaryLUTs', action='store_true')
1803     p.add_option('--keepTempImages', action='store_true')
1804
1805     options, arguments = p.parse_args()
1806
1807     #
1808     # Get options
1809     #
1810     aces_CTL_directory = options.acesCTLDir
1811     config_directory = options.configDir
1812     lut_resolution_1d = int(options.lutResolution1d)
1813     lut_resolution_3d = int(options.lutResolution3d)
1814     bake_secondary_LUTs = not (options.dontBakeSecondaryLUTs)
1815     cleanup_temp_images = not (options.keepTempImages)
1816
1817     try:
1818         args_start = sys.argv.index('--') + 1
1819         args = sys.argv[args_start:]
1820     except:
1821         args_start = len(sys.argv) + 1
1822         args = []
1823
1824     print('command line : \n%s\n' % ' '.join(sys.argv))
1825
1826     # TODO: Use assertion and mention environment variables.
1827     if not aces_CTL_directory:
1828         print('process: No ACES CTL directory specified')
1829         return
1830     if not config_directory:
1831         print('process: No configuration directory specified')
1832         return
1833     #
1834     # Generate the configuration
1835     #
1836     return create_ACES_config(aces_CTL_directory,
1837                               config_directory,
1838                               lut_resolution_1d,
1839                               lut_resolution_3d,
1840                               bake_secondary_LUTs,
1841                               cleanup_temp_images)
1842
1843
1844 if __name__ == '__main__':
1845     main()