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