e59fb618a862fd7387b1ecd20635cebc943f5d95
[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             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             '%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             os.path.join(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(os.path.join(lut_directory, lut),
672                          RANGE[0],
673                          RANGE[1],
674                          data,
675                          NUM_SAMPLES, 1)
676
677             return lut
678
679         # Convert Channel Independent Density values to Relative Log Exposure
680         # values.
681         lut = create_CID_to_RLE_LUT()
682         cs.to_reference_transforms.append({
683             'type': 'lutFile',
684             'path': lut,
685             'interpolation': 'linear',
686             'direction': 'forward'
687         })
688
689         # Convert Relative Log Exposure values to Relative Exposure values
690         cs.to_reference_transforms.append({
691             'type': 'log',
692             'base': 10,
693             'direction': 'inverse'
694         })
695
696         # Convert Relative Exposure values to ACES values
697         cs.to_reference_transforms.append({
698             'type': 'matrix',
699             'matrix': [0.72286, 0.12630, 0.15084, 0,
700                        0.11923, 0.76418, 0.11659, 0,
701                        0.01427, 0.08213, 0.90359, 0,
702                        0.0, 0.0, 0.0, 1.0],
703             'direction': 'forward'
704         })
705
706         cs.from_reference_transforms = []
707         return cs
708
709     ADX10 = create_ADX(bit_depth=10)
710     config_data['colorSpaces'].append(ADX10)
711
712     ADX16 = create_ADX(bit_depth=16)
713     config_data['colorSpaces'].append(ADX16)
714
715     #
716     # Camera Input Transforms
717     #
718
719     # RED color spaces to ACES
720     red_colorspaces = red.create_colorspaces(lut_directory, lut_resolution_1d)
721     for cs in red_colorspaces:
722         config_data['colorSpaces'].append(cs)
723
724     # Canon-Log to ACES
725     canon_colorspaces = canon.create_colorspaces(lut_directory,
726                                                  lut_resolution_1d)
727     for cs in canon_colorspaces:
728         config_data['colorSpaces'].append(cs)
729
730     # S-Log to ACES
731     sony_colorSpaces = sony.create_colorspaces(lut_directory,
732                                                lut_resolution_1d)
733     for cs in sony_colorSpaces:
734         config_data['colorSpaces'].append(cs)
735
736     # Log-C to ACES
737     arri_colorSpaces = arri.create_colorspaces(lut_directory,
738                                                lut_resolution_1d)
739     for cs in arri_colorSpaces:
740         config_data['colorSpaces'].append(cs)
741
742     #
743     # Generic log transform
744     #
745     def create_generic_log(name='log',
746                            min_value=0.0,
747                            max_value=1.0,
748                            input_scale=1.0,
749                            middle_grey=0.18,
750                            min_exposure=-6.0,
751                            max_exposure=6.5,
752                            lut_resolution_1d=lut_resolution_1d):
753         cs = ColorSpace(name)
754         cs.description = 'The %s color space' % name
755         cs.equality_group = name
756         cs.family = 'Utility'
757         cs.is_data = False
758
759         ctls = [
760             '%s/utilities/ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl' % (
761                 aces_CTL_directory)]
762         lut = '%s_to_aces.spi1d' % name
763
764         # Remove spaces and parentheses
765         lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
766
767         generate_1d_LUT_from_CTL(
768             os.path.join(lut_directory, lut),
769             ctls,
770             lut_resolution_1d,
771             'float',
772             input_scale,
773             1.0,
774             {
775                 'middleGrey': middle_grey,
776                 'minExposure': min_exposure,
777                 'maxExposure': max_exposure
778             },
779             cleanup,
780             aces_CTL_directory,
781             min_value,
782             max_value)
783
784         cs.to_reference_transforms = []
785         cs.to_reference_transforms.append({
786             'type': 'lutFile',
787             'path': lut,
788             'interpolation': 'linear',
789             'direction': 'forward'
790         })
791
792         cs.from_reference_transforms = []
793         return cs
794
795     #
796     # ACES LMTs
797     #
798     def create_ACES_LMT(lmt_name,
799                         lmt_values,
800                         shaper_info,
801                         lut_resolution_1d=1024,
802                         lut_resolution_3d=64,
803                         cleanup=True):
804         cs = ColorSpace('%s' % lmt_name)
805         cs.description = 'The ACES Look Transform: %s' % lmt_name
806         cs.equality_group = ''
807         cs.family = 'Look'
808         cs.is_data = False
809
810         pprint.pprint(lmt_values)
811
812         #
813         # Generate the shaper transform
814         #
815         (shaper_name,
816          shaper_to_ACES_CTL,
817          shaper_from_ACES_CTL,
818          shaper_input_scale,
819          shaper_params) = shaper_info
820
821         shaper_lut = '%s_to_aces.spi1d' % shaper_name
822         if (not os.path.exists(os.path.join(lut_directory, shaper_lut))):
823             ctls = [shaper_to_ACES_CTL % aces_CTL_directory]
824
825             # Remove spaces and parentheses
826             shaper_lut = shaper_lut.replace(
827                 ' ', '_').replace(')', '_').replace('(', '_')
828
829             generate_1d_LUT_from_CTL(
830                 os.path.join(lut_directory, shaper_lut),
831                 ctls,
832                 lut_resolution_1d,
833                 'float',
834                 1.0 / shaper_input_scale,
835                 1.0,
836                 shaper_params,
837                 cleanup,
838                 aces_CTL_directory)
839
840         shaper_OCIO_transform = {
841             'type': 'lutFile',
842             'path': shaper_lut,
843             'interpolation': 'linear',
844             'direction': 'inverse'
845         }
846
847         #
848         # Generate the forward transform
849         #
850         cs.from_reference_transforms = []
851
852         if 'transformCTL' in lmt_values:
853             ctls = [
854                 shaper_to_ACES_CTL % aces_CTL_directory,
855                 '%s/%s' % (aces_CTL_directory, lmt_values['transformCTL'])
856             ]
857             lut = '%s.%s.spi3d' % (shaper_name, lmt_name)
858
859             # Remove spaces and parentheses
860             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
861
862             generate_3d_LUT_from_CTL(
863                 os.path.join(lut_directory, lut),
864                 ctls,
865                 lut_resolution_3d,
866                 'float',
867                 1.0 / shaper_input_scale,
868                 1.0,
869                 shaper_params,
870                 cleanup,
871                 aces_CTL_directory)
872
873             cs.from_reference_transforms.append(shaper_OCIO_transform)
874             cs.from_reference_transforms.append({
875                 'type': 'lutFile',
876                 'path': lut,
877                 'interpolation': 'tetrahedral',
878                 'direction': 'forward'
879             })
880
881         #
882         # Generate the inverse transform
883         #
884         cs.to_reference_transforms = []
885
886         if 'transformCTLInverse' in lmt_values:
887             ctls = [
888                 '%s/%s' % (
889                     aces_CTL_directory, odt_values['transformCTLInverse']),
890                 shaper_from_ACES_CTL % aces_CTL_directory
891             ]
892             lut = 'Inverse.%s.%s.spi3d' % (odt_name, shaper_name)
893
894             # Remove spaces and parentheses
895             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
896
897             generate_3d_LUT_from_CTL(
898                 os.path.join(lut_directory, lut),
899                 ctls,
900                 lut_resolution_3d,
901                 'half',
902                 1.0,
903                 shaper_input_scale,
904                 shaper_params,
905                 cleanup,
906                 aces_CTL_directory)
907
908             cs.to_reference_transforms.append({
909                 'type': 'lutFile',
910                 'path': lut,
911                 'interpolation': 'tetrahedral',
912                 'direction': 'forward'
913             })
914
915             shaper_inverse = shaper_OCIO_transform.copy()
916             shaper_inverse['direction'] = 'forward'
917             cs.to_reference_transforms.append(shaper_inverse)
918
919         return cs
920
921     #
922     # LMT Shaper
923     #
924
925     lmt_lut_resolution_1d = max(4096, lut_resolution_1d)
926     lmt_lut_resolution_3d = max(65, lut_resolution_3d)
927
928     # Log 2 shaper
929     lmt_shaper_name = 'LMT Shaper'
930     lmt_params = {
931         'middleGrey': 0.18,
932         'minExposure': -10.0,
933         'maxExposure': 6.5
934     }
935     lmt_shaper = create_generic_log(name=lmt_shaper_name,
936                                     middle_grey=lmt_params['middleGrey'],
937                                     min_exposure=lmt_params['minExposure'],
938                                     max_exposure=lmt_params['maxExposure'],
939                                     lut_resolution_1d=lmt_lut_resolution_1d)
940     config_data['colorSpaces'].append(lmt_shaper)
941
942     shaper_input_scale_generic_log2 = 1.0
943
944     # Log 2 shaper name and CTL transforms bundled up
945     lmt_shaper_data = [
946         lmt_shaper_name,
947         '%s/utilities/ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl',
948         '%s/utilities/ACESlib.OCIO_shaper_lin_to_log2_param.a1.0.0.ctl',
949         shaper_input_scale_generic_log2,
950         lmt_params
951     ]
952
953     sorted_LMTs = sorted(lmt_info.iteritems(), key=lambda x: x[1])
954     print(sorted_LMTs)
955     for lmt in sorted_LMTs:
956         (lmt_name, lmt_values) = lmt
957         cs = create_ACES_LMT(
958             lmt_values['transformUserName'],
959             lmt_values,
960             lmt_shaper_data,
961             lmt_lut_resolution_1d,
962             lmt_lut_resolution_3d,
963             cleanup)
964         config_data['colorSpaces'].append(cs)
965
966     #
967     # ACES RRT with the supplied ODT
968     #
969     def create_ACES_RRT_plus_ODT(odt_name,
970                                  odt_values,
971                                  shaper_info,
972                                  lut_resolution_1d=1024,
973                                  lut_resolution_3d=64,
974                                  cleanup=True):
975         cs = ColorSpace('%s' % odt_name)
976         cs.description = '%s - %s Output Transform' % (
977             odt_values['transformUserNamePrefix'], odt_name)
978         cs.equality_group = ''
979         cs.family = 'Output'
980         cs.is_data = False
981
982         pprint.pprint(odt_values)
983
984         #
985         # Generate the shaper transform
986         #
987         # if 'shaperCTL' in odtValues:
988         (shaper_name,
989          shaper_to_ACES_CTL,
990          shaper_from_ACES_CTL,
991          shaper_input_scale,
992          shaper_params) = shaper_info
993
994         if 'legalRange' in odt_values:
995             shaper_params['legalRange'] = odt_values['legalRange']
996         else:
997             shaper_params['legalRange'] = 0
998
999         shaper_lut = '%s_to_aces.spi1d' % shaper_name
1000         if (not os.path.exists(os.path.join(lut_directory, shaper_lut))):
1001             ctls = [shaper_to_ACES_CTL % aces_CTL_directory]
1002
1003             # Remove spaces and parentheses
1004             shaper_lut = shaper_lut.replace(
1005                 ' ', '_').replace(')', '_').replace('(', '_')
1006
1007             generate_1d_LUT_from_CTL(
1008                 os.path.join(lut_directory, shaper_lut),
1009                 ctls,
1010                 lut_resolution_1d,
1011                 'float',
1012                 1.0 / shaper_input_scale,
1013                 1.0,
1014                 shaper_params,
1015                 cleanup,
1016                 aces_CTL_directory)
1017
1018         shaper_OCIO_transform = {
1019             'type': 'lutFile',
1020             'path': shaper_lut,
1021             'interpolation': 'linear',
1022             'direction': 'inverse'
1023         }
1024
1025         #
1026         # Generate the forward transform
1027         #
1028         cs.from_reference_transforms = []
1029
1030         if 'transformLUT' in odt_values:
1031             # Copy into the lut dir
1032             transform_LUT_file_name = os.path.basename(
1033                 odt_values['transformLUT'])
1034             lut = os.path.join(lut_directory, transform_LUT_file_name)
1035             shutil.copy(odt_values['transformLUT'], lut)
1036
1037             cs.from_reference_transforms.append(shaper_OCIO_transform)
1038             cs.from_reference_transforms.append({
1039                 'type': 'lutFile',
1040                 'path': transform_LUT_file_name,
1041                 'interpolation': 'tetrahedral',
1042                 'direction': 'forward'
1043             })
1044         elif 'transformCTL' in odt_values:
1045             # shaperLut
1046
1047             ctls = [
1048                 shaper_to_ACES_CTL % aces_CTL_directory,
1049                 '%s/rrt/RRT.a1.0.0.ctl' % aces_CTL_directory,
1050                 '%s/odt/%s' % (aces_CTL_directory, odt_values['transformCTL'])
1051             ]
1052             lut = '%s.RRT.a1.0.0.%s.spi3d' % (shaper_name, odt_name)
1053
1054             # Remove spaces and parentheses
1055             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
1056
1057             generate_3d_LUT_from_CTL(
1058                 os.path.join(lut_directory, lut),
1059                 # shaperLUT,
1060                 ctls,
1061                 lut_resolution_3d,
1062                 'float',
1063                 1.0 / shaper_input_scale,
1064                 1.0,
1065                 shaper_params,
1066                 cleanup,
1067                 aces_CTL_directory)
1068
1069             cs.from_reference_transforms.append(shaper_OCIO_transform)
1070             cs.from_reference_transforms.append({
1071                 'type': 'lutFile',
1072                 'path': lut,
1073                 'interpolation': 'tetrahedral',
1074                 'direction': 'forward'
1075             })
1076
1077         #
1078         # Generate the inverse transform
1079         #
1080         cs.to_reference_transforms = []
1081
1082         if 'transformLUTInverse' in odt_values:
1083             # Copy into the lut dir
1084             transform_LUT_inverse_file_name = os.path.basename(
1085                 odt_values['transformLUTInverse'])
1086             lut = os.path.join(lut_directory, transform_LUT_inverse_file_name)
1087             shutil.copy(odt_values['transformLUTInverse'], lut)
1088
1089             cs.to_reference_transforms.append({
1090                 'type': 'lutFile',
1091                 'path': transform_LUT_inverse_file_name,
1092                 'interpolation': 'tetrahedral',
1093                 'direction': 'forward'
1094             })
1095
1096             shaper_inverse = shaper_OCIO_transform.copy()
1097             shaper_inverse['direction'] = 'forward'
1098             cs.to_reference_transforms.append(shaper_inverse)
1099         elif 'transformCTLInverse' in odt_values:
1100             ctls = [
1101                 '%s/odt/%s' % (
1102                     aces_CTL_directory, odt_values['transformCTLInverse']),
1103                 '%s/rrt/InvRRT.a1.0.0.ctl' % aces_CTL_directory,
1104                 shaper_from_ACES_CTL % aces_CTL_directory
1105             ]
1106             lut = 'InvRRT.a1.0.0.%s.%s.spi3d' % (odt_name, shaper_name)
1107
1108             # Remove spaces and parentheses
1109             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
1110
1111             generate_3d_LUT_from_CTL(
1112                 os.path.join(lut_directory, lut),
1113                 # None,
1114                 ctls,
1115                 lut_resolution_3d,
1116                 'half',
1117                 1.0,
1118                 shaper_input_scale,
1119                 shaper_params,
1120                 cleanup,
1121                 aces_CTL_directory)
1122
1123             cs.to_reference_transforms.append({
1124                 'type': 'lutFile',
1125                 'path': lut,
1126                 'interpolation': 'tetrahedral',
1127                 'direction': 'forward'
1128             })
1129
1130             shaper_inverse = shaper_OCIO_transform.copy()
1131             shaper_inverse['direction'] = 'forward'
1132             cs.to_reference_transforms.append(shaper_inverse)
1133
1134         return cs
1135
1136     #
1137     # RRT/ODT shaper options
1138     #
1139     shaper_data = {}
1140
1141     # Log 2 shaper
1142     log2_shaper_name = shaper_name
1143     log2_params = {
1144         'middleGrey': 0.18,
1145         'minExposure': -6.0,
1146         'maxExposure': 6.5
1147     }
1148     log2_shaper = create_generic_log(
1149         name=log2_shaper_name,
1150         middle_grey=log2_params['middleGrey'],
1151         min_exposure=log2_params['minExposure'],
1152         max_exposure=log2_params['maxExposure'])
1153     config_data['colorSpaces'].append(log2_shaper)
1154
1155     shaper_input_scale_generic_log2 = 1.0
1156
1157     # Log 2 shaper name and CTL transforms bundled up
1158     log2_shaper_data = [
1159         log2_shaper_name,
1160         '%s/utilities/ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl',
1161         '%s/utilities/ACESlib.OCIO_shaper_lin_to_log2_param.a1.0.0.ctl',
1162         shaper_input_scale_generic_log2,
1163         log2_params
1164     ]
1165
1166     shaper_data[log2_shaper_name] = log2_shaper_data
1167
1168     #
1169     # Shaper that also includes the AP1 primaries
1170     # - Needed for some LUT baking steps
1171     #
1172     log2_shaper_AP1 = create_generic_log(
1173         name=log2_shaper_name,
1174         middle_grey=log2_params['middleGrey'],
1175         min_exposure=log2_params['minExposure'],
1176         max_exposure=log2_params['maxExposure'])
1177     log2_shaper_AP1.name = '%s - AP1' % log2_shaper_AP1.name
1178     # AP1 primaries to AP0 primaries
1179     log2_shaper_AP1.to_reference_transforms.append({
1180         'type': 'matrix',
1181         'matrix': mat44_from_mat33(ACES_AP1_to_AP0),
1182         'direction': 'forward'
1183     })
1184     config_data['colorSpaces'].append(log2_shaper_AP1)
1185
1186     #
1187     # Choose your shaper
1188     #
1189     rrt_shaper_name = log2_shaper_name
1190     rrt_shaper = log2_shaper_data
1191
1192     #
1193     # RRT + ODT Combinations
1194     #
1195     sorted_odts = sorted(odt_info.iteritems(), key=lambda x: x[1])
1196     print(sorted_odts)
1197     for odt in sorted_odts:
1198         (odt_name, odt_values) = odt
1199
1200         # Have to handle ODTs that can generate either legal or full output
1201         if odt_name in ['Academy.Rec2020_100nits_dim.a1.0.0',
1202                         'Academy.Rec709_100nits_dim.a1.0.0',
1203                         'Academy.Rec709_D60sim_100nits_dim.a1.0.0']:
1204             odt_name_legal = '%s - Legal' % odt_values['transformUserName']
1205         else:
1206             odt_name_legal = odt_values['transformUserName']
1207
1208         odt_legal = odt_values.copy()
1209         odt_legal['legalRange'] = 1
1210
1211         cs = create_ACES_RRT_plus_ODT(
1212             odt_name_legal,
1213             odt_legal,
1214             rrt_shaper,
1215             lut_resolution_1d,
1216             lut_resolution_3d,
1217             cleanup)
1218         config_data['colorSpaces'].append(cs)
1219
1220         # Create a display entry using this color space
1221         config_data['displays'][odt_name_legal] = {
1222             'Linear': ACES,
1223             'Log': ACEScc,
1224             'Output Transform': cs}
1225
1226         if odt_name in ['Academy.Rec2020_100nits_dim.a1.0.0',
1227                         'Academy.Rec709_100nits_dim.a1.0.0',
1228                         'Academy.Rec709_D60sim_100nits_dim.a1.0.0']:
1229             print('Generating full range ODT for %s' % odt_name)
1230
1231             odt_name_full = '%s - Full' % odt_values['transformUserName']
1232             odt_full = odt_values.copy()
1233             odt_full['legalRange'] = 0
1234
1235             cs_full = create_ACES_RRT_plus_ODT(
1236                 odt_name_full,
1237                 odt_full,
1238                 rrt_shaper,
1239                 lut_resolution_1d,
1240                 lut_resolution_3d,
1241                 cleanup)
1242             config_data['colorSpaces'].append(cs_full)
1243
1244             # Create a display entry using this color space
1245             config_data['displays'][odt_name_full] = {
1246                 'Linear': ACES,
1247                 'Log': ACEScc,
1248                 'Output Transform': cs_full}
1249
1250     #
1251     # Generic Matrix transform
1252     #
1253     def create_generic_matrix(name='matrix',
1254                               from_reference_values=[],
1255                               to_reference_values=[]):
1256         cs = ColorSpace(name)
1257         cs.description = 'The %s color space' % name
1258         cs.equality_group = name
1259         cs.family = 'Utility'
1260         cs.is_data = False
1261
1262         cs.to_reference_transforms = []
1263         if to_reference_values != []:
1264             for matrix in to_reference_values:
1265                 cs.to_reference_transforms.append({
1266                     'type': 'matrix',
1267                     'matrix': mat44_from_mat33(matrix),
1268                     'direction': 'forward'
1269                 })
1270
1271         cs.from_reference_transforms = []
1272         if from_reference_values != []:
1273             for matrix in from_reference_values:
1274                 cs.from_reference_transforms.append({
1275                     'type': 'matrix',
1276                     'matrix': mat44_from_mat33(matrix),
1277                     'direction': 'forward'
1278                 })
1279
1280         return cs
1281
1282     cs = create_generic_matrix('XYZ', from_reference_values=[ACES_AP0_to_XYZ])
1283     config_data['colorSpaces'].append(cs)
1284
1285     cs = create_generic_matrix(
1286         'Linear - AP1', to_reference_values=[ACES_AP1_to_AP0])
1287     config_data['colorSpaces'].append(cs)
1288
1289     # ACES to Linear, P3D60 primaries
1290     XYZ_to_P3D60 = [2.4027414142, -0.8974841639, -0.3880533700,
1291                     -0.8325796487, 1.7692317536, 0.0237127115,
1292                     0.0388233815, -0.0824996856, 1.0363685997]
1293
1294     cs = create_generic_matrix(
1295         'Linear - P3-D60',
1296         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_P3D60])
1297     config_data['colorSpaces'].append(cs)
1298
1299     # ACES to Linear, P3D60 primaries
1300     XYZ_to_P3DCI = [2.7253940305, -1.0180030062, -0.4401631952,
1301                     -0.7951680258, 1.6897320548, 0.0226471906,
1302                     0.0412418914, -0.0876390192, 1.1009293786]
1303
1304     cs = create_generic_matrix(
1305         'Linear - P3-DCI',
1306         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_P3DCI])
1307     config_data['colorSpaces'].append(cs)
1308
1309     # ACES to Linear, Rec 709 primaries
1310     XYZ_to_Rec709 = [3.2409699419, -1.5373831776, -0.4986107603,
1311                      -0.9692436363, 1.8759675015, 0.0415550574,
1312                      0.0556300797, -0.2039769589, 1.0569715142]
1313
1314     cs = create_generic_matrix(
1315         'Linear - Rec.709',
1316         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_Rec709])
1317     config_data['colorSpaces'].append(cs)
1318
1319     # ACES to Linear, Rec 2020 primaries
1320     XYZ_to_Rec2020 = [1.7166511880, -0.3556707838, -0.2533662814,
1321                       -0.6666843518, 1.6164812366, 0.0157685458,
1322                       0.0176398574, -0.0427706133, 0.9421031212]
1323
1324     cs = create_generic_matrix(
1325         'Linear - Rec.2020',
1326         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_Rec2020])
1327     config_data['colorSpaces'].append(cs)
1328
1329     print('generateLUTs - end')
1330     return config_data
1331
1332
1333 def generate_baked_LUTs(odt_info,
1334                         shaper_name,
1335                         baked_directory,
1336                         config_path,
1337                         lut_resolution_1d,
1338                         lut_resolution_3d,
1339                         lut_resolution_shaper=1024):
1340     """
1341     Object description.
1342
1343     Parameters
1344     ----------
1345     parameter : type
1346         Parameter description.
1347
1348     Returns
1349     -------
1350     type
1351          Return value description.
1352     """
1353
1354     # Add the legal and full variations into this list
1355     odt_info_C = dict(odt_info)
1356     for odt_CTL_name, odt_values in odt_info.iteritems():
1357         if odt_CTL_name in ['Academy.Rec2020_100nits_dim.a1.0.0',
1358                             'Academy.Rec709_100nits_dim.a1.0.0',
1359                             'Academy.Rec709_D60sim_100nits_dim.a1.0.0']:
1360             odt_name = odt_values['transformUserName']
1361
1362             odt_values_legal = dict(odt_values)
1363             odt_values_legal['transformUserName'] = '%s - Legal' % odt_name
1364             odt_info_C['%s - Legal' % odt_CTL_name] = odt_values_legal
1365
1366             odt_values_full = dict(odt_values)
1367             odt_values_full['transformUserName'] = '%s - Full' % odt_name
1368             odt_info_C['%s - Full' % odt_CTL_name] = odt_values_full
1369
1370             del (odt_info_C[odt_CTL_name])
1371
1372     for odt_CTL_name, odt_values in odt_info_C.iteritems():
1373         odt_prefix = odt_values['transformUserNamePrefix']
1374         odt_name = odt_values['transformUserName']
1375
1376         # For Photoshop
1377         for input_space in ['ACEScc', 'ACESproxy']:
1378             args = ['--iconfig', config_path,
1379                     '-v',
1380                     '--inputspace', input_space]
1381             args += ['--outputspace', '%s' % odt_name]
1382             args += ['--description',
1383                      '%s - %s for %s data' % (odt_prefix,
1384                                               odt_name,
1385                                               input_space)]
1386             args += ['--shaperspace', shaper_name,
1387                      '--shapersize', str(lut_resolution_shaper)]
1388             args += ['--cubesize', str(lut_resolution_3d)]
1389             args += ['--format',
1390                      'icc',
1391                      '%s/photoshop/%s for %s.icc' % (baked_directory,
1392                                                      odt_name,
1393                                                      input_space)]
1394
1395             bake_LUT = Process(description='bake a LUT',
1396                                cmd='ociobakelut',
1397                                args=args)
1398             bake_LUT.execute()
1399
1400         # For Flame, Lustre
1401         for input_space in ['ACEScc', 'ACESproxy']:
1402             args = ['--iconfig', config_path,
1403                     '-v',
1404                     '--inputspace', input_space]
1405             args += ['--outputspace', '%s' % odt_name]
1406             args += ['--description',
1407                      '%s - %s for %s data' % (
1408                          odt_prefix, odt_name, input_space)]
1409             args += ['--shaperspace', shaper_name,
1410                      '--shapersize', str(lut_resolution_shaper)]
1411             args += ['--cubesize', str(lut_resolution_3d)]
1412
1413             fargs = ['--format', 'flame', '%s/flame/%s for %s Flame.3dl' % (
1414                 baked_directory, odt_name, input_space)]
1415             bake_LUT = Process(description='bake a LUT',
1416                                cmd='ociobakelut',
1417                                args=(args + fargs))
1418             bake_LUT.execute()
1419
1420             largs = ['--format', 'lustre', '%s/lustre/%s for %s Lustre.3dl' % (
1421                 baked_directory, odt_name, input_space)]
1422             bake_LUT = Process(description='bake a LUT',
1423                                cmd='ociobakelut',
1424                                args=(args + largs))
1425             bake_LUT.execute()
1426
1427         # For Maya, Houdini
1428         for input_space in ['ACEScg', 'ACES2065-1']:
1429             args = ['--iconfig', config_path,
1430                     '-v',
1431                     '--inputspace', input_space]
1432             args += ['--outputspace', '%s' % odt_name]
1433             args += ['--description',
1434                      '%s - %s for %s data' % (
1435                          odt_prefix, odt_name, input_space)]
1436             if input_space == 'ACEScg':
1437                 lin_shaper_name = '%s - AP1' % shaper_name
1438             else:
1439                 lin_shaper_name = shaper_name
1440             args += ['--shaperspace', lin_shaper_name,
1441                      '--shapersize', str(lut_resolution_shaper)]
1442
1443             args += ['--cubesize', str(lut_resolution_3d)]
1444
1445             margs = ['--format', 'cinespace', '%s/maya/%s for %s Maya.csp' % (
1446                 baked_directory, odt_name, input_space)]
1447             bake_LUT = Process(description='bake a LUT',
1448                                cmd='ociobakelut',
1449                                args=(args + margs))
1450             bake_LUT.execute()
1451
1452             hargs = ['--format', 'houdini',
1453                      '%s/houdini/%s for %s Houdini.lut' % (
1454                          baked_directory, odt_name, input_space)]
1455             bake_LUT = Process(description='bake a LUT',
1456                                cmd='ociobakelut',
1457                                args=(args + hargs))
1458             bake_LUT.execute()
1459
1460
1461 def create_config_dir(config_directory, bake_secondary_LUTs):
1462     """
1463     Object description.
1464
1465     Parameters
1466     ----------
1467     parameter : type
1468         Parameter description.
1469
1470     Returns
1471     -------
1472     type
1473          Return value description.
1474     """
1475
1476     dirs = [config_directory, '%s/luts' % config_directory]
1477     if bake_secondary_LUTs:
1478         dirs.extend(['%s/baked' % config_directory,
1479                      '%s/baked/flame' % config_directory,
1480                      '%s/baked/photoshop' % config_directory,
1481                      '%s/baked/houdini' % config_directory,
1482                      '%s/baked/lustre' % config_directory,
1483                      '%s/baked/maya' % config_directory])
1484
1485     for d in dirs:
1486         not os.path.exists(d) and os.mkdir(d)
1487
1488
1489 def get_transform_info(ctl_transform):
1490     """
1491     Object description.
1492
1493     Parameters
1494     ----------
1495     parameter : type
1496         Parameter description.
1497
1498     Returns
1499     -------
1500     type
1501          Return value description.
1502     """
1503
1504     # TODO: Use *with* statement.
1505     fp = open(ctl_transform, 'rb')
1506
1507     # Read lines
1508     lines = fp.readlines()
1509
1510     # Grab transform ID and User Name
1511     transform_ID = lines[1][3:].split('<')[1].split('>')[1].strip()
1512     # print(transformID)
1513     transform_user_name = '-'.join(
1514         lines[2][3:].split('<')[1].split('>')[1].split('-')[1:]).strip()
1515     transform_user_name_prefix = (
1516         lines[2][3:].split('<')[1].split('>')[1].split('-')[0].strip())
1517     # print(transformUserName)
1518     fp.close()
1519
1520     return transform_ID, transform_user_name, transform_user_name_prefix
1521
1522
1523 def get_ODT_info(aces_CTL_directory):
1524     """
1525     Object description.
1526
1527     For versions after WGR9.
1528
1529     Parameters
1530     ----------
1531     parameter : type
1532         Parameter description.
1533
1534     Returns
1535     -------
1536     type
1537          Return value description.
1538     """
1539
1540     # TODO: Investigate usage of *files_walker* definition here.
1541     # Credit to Alex Fry for the original approach here
1542     odt_dir = os.path.join(aces_CTL_directory, 'odt')
1543     all_odt = []
1544     for dir_name, subdir_list, file_list in os.walk(odt_dir):
1545         for fname in file_list:
1546             all_odt.append((os.path.join(dir_name, fname)))
1547
1548     odt_CTLs = [x for x in all_odt if
1549                 ('InvODT' not in x) and (os.path.split(x)[-1][0] != '.')]
1550
1551     # print odtCTLs
1552
1553     odts = {}
1554
1555     for odt_CTL in odt_CTLs:
1556         odt_tokens = os.path.split(odt_CTL)
1557         # print(odtTokens)
1558
1559         # Handle nested directories
1560         odt_path_tokens = os.path.split(odt_tokens[-2])
1561         odt_dir = odt_path_tokens[-1]
1562         while odt_path_tokens[-2][-3:] != 'odt':
1563             odt_path_tokens = os.path.split(odt_path_tokens[-2])
1564             odt_dir = os.path.join(odt_path_tokens[-1], odt_dir)
1565
1566         # Build full name
1567         # print('odtDir : %s' % odtDir)
1568         transform_CTL = odt_tokens[-1]
1569         # print(transformCTL)
1570         odt_name = string.join(transform_CTL.split('.')[1:-1], '.')
1571         # print(odtName)
1572
1573         # Find id, user name and user name prefix
1574         (transform_ID,
1575          transform_user_name,
1576          transform_user_name_prefix) = get_transform_info(
1577             '%s/odt/%s/%s' % (aces_CTL_directory, odt_dir, transform_CTL))
1578
1579         # Find inverse
1580         transform_CTL_inverse = 'InvODT.%s.ctl' % odt_name
1581         if not os.path.exists(
1582                 os.path.join(odt_tokens[-2], transform_CTL_inverse)):
1583             transform_CTL_inverse = None
1584         # print(transformCTLInverse)
1585
1586         # Add to list of ODTs
1587         odts[odt_name] = {}
1588         odts[odt_name]['transformCTL'] = os.path.join(odt_dir, transform_CTL)
1589         if transform_CTL_inverse != None:
1590             odts[odt_name]['transformCTLInverse'] = os.path.join(
1591                 odt_dir, transform_CTL_inverse)
1592
1593         odts[odt_name]['transformID'] = transform_ID
1594         odts[odt_name]['transformUserNamePrefix'] = transform_user_name_prefix
1595         odts[odt_name]['transformUserName'] = transform_user_name
1596
1597         print('ODT : %s' % odt_name)
1598         print('\tTransform ID               : %s' % transform_ID)
1599         print('\tTransform User Name Prefix : %s' % transform_user_name_prefix)
1600         print('\tTransform User Name        : %s' % transform_user_name)
1601         print('\tForward ctl                : %s' % (
1602             odts[odt_name]['transformCTL']))
1603         if 'transformCTLInverse' in odts[odt_name]:
1604             print('\tInverse ctl                : %s' % (
1605                 odts[odt_name]['transformCTLInverse']))
1606         else:
1607             print('\tInverse ctl                : %s' % 'None')
1608
1609     print('\n')
1610
1611     return odts
1612
1613
1614 def get_LMT_info(aces_CTL_directory):
1615     """
1616     Object description.
1617
1618     For versions after WGR9.
1619
1620     Parameters
1621     ----------
1622     parameter : type
1623         Parameter description.
1624
1625     Returns
1626     -------
1627     type
1628          Return value description.
1629     """
1630
1631     # TODO: Investigate refactoring with previous definition.
1632
1633     # Credit to Alex Fry for the original approach here
1634     lmt_dir = os.path.join(aces_CTL_directory, 'lmt')
1635     all_lmt = []
1636     for dir_name, subdir_list, file_list in os.walk(lmt_dir):
1637         for fname in file_list:
1638             all_lmt.append((os.path.join(dir_name, fname)))
1639
1640     lmt_CTLs = [x for x in all_lmt if
1641                 ('InvLMT' not in x) and ('README' not in x) and (
1642                     os.path.split(x)[-1][0] != '.')]
1643
1644     # print lmtCTLs
1645
1646     lmts = {}
1647
1648     for lmt_CTL in lmt_CTLs:
1649         lmt_tokens = os.path.split(lmt_CTL)
1650         # print(lmtTokens)
1651
1652         # Handle nested directories
1653         lmt_path_tokens = os.path.split(lmt_tokens[-2])
1654         lmt_dir = lmt_path_tokens[-1]
1655         while lmt_path_tokens[-2][-3:] != 'ctl':
1656             lmt_path_tokens = os.path.split(lmt_path_tokens[-2])
1657             lmt_dir = os.path.join(lmt_path_tokens[-1], lmt_dir)
1658
1659         # Build full name
1660         # print('lmtDir : %s' % lmtDir)
1661         transform_CTL = lmt_tokens[-1]
1662         # print(transformCTL)
1663         lmt_name = string.join(transform_CTL.split('.')[1:-1], '.')
1664         # print(lmtName)
1665
1666         # Find id, user name and user name prefix
1667         (transform_ID,
1668          transform_user_name,
1669          transform_user_name_prefix) = get_transform_info(
1670             '%s/%s/%s' % (aces_CTL_directory, lmt_dir, transform_CTL))
1671
1672         # Find inverse
1673         transform_CTL_inverse = 'InvLMT.%s.ctl' % lmt_name
1674         if not os.path.exists(
1675                 os.path.join(lmt_tokens[-2], transform_CTL_inverse)):
1676             transform_CTL_inverse = None
1677         # print(transformCTLInverse)
1678
1679         # Add to list of LMTs
1680         lmts[lmt_name] = {}
1681         lmts[lmt_name]['transformCTL'] = os.path.join(lmt_dir, transform_CTL)
1682         if transform_CTL_inverse != None:
1683             # TODO: Check unresolved *odt_name* referemce.
1684             lmts[odt_name]['transformCTLInverse'] = os.path.join(
1685                 lmt_dir, transform_CTL_inverse)
1686
1687         lmts[lmt_name]['transformID'] = transform_ID
1688         lmts[lmt_name]['transformUserNamePrefix'] = transform_user_name_prefix
1689         lmts[lmt_name]['transformUserName'] = transform_user_name
1690
1691         print('LMT : %s' % lmt_name)
1692         print('\tTransform ID               : %s' % transform_ID)
1693         print('\tTransform User Name Prefix : %s' % transform_user_name_prefix)
1694         print('\tTransform User Name        : %s' % transform_user_name)
1695         print('\t Forward ctl : %s' % lmts[lmt_name]['transformCTL'])
1696         if 'transformCTLInverse' in lmts[lmt_name]:
1697             print('\t Inverse ctl : %s' % (
1698                 lmts[lmt_name]['transformCTLInverse']))
1699         else:
1700             print('\t Inverse ctl : %s' % 'None')
1701
1702     print('\n')
1703
1704     return lmts
1705
1706
1707 def create_ACES_config(aces_CTL_directory,
1708                        config_directory,
1709                        lut_resolution_1d=4096,
1710                        lut_resolution_3d=64,
1711                        bake_secondary_LUTs=True,
1712                        cleanup=True):
1713     """
1714     Creates the ACES configuration.
1715
1716     Parameters
1717     ----------
1718     parameter : type
1719         Parameter description.
1720
1721     Returns
1722     -------
1723     type
1724          Return value description.
1725     """
1726
1727     # Get ODT names and CTL paths
1728     odt_info = get_ODT_info(aces_CTL_directory)
1729
1730     # Get ODT names and CTL paths
1731     lmt_info = get_LMT_info(aces_CTL_directory)
1732
1733     # Create config dir
1734     create_config_dir(config_directory, bake_secondary_LUTs)
1735
1736     # Generate config data and LUTs for different transforms
1737     lut_directory = '%s/luts' % config_directory
1738     shaper_name = 'Output Shaper'
1739     config_data = generate_LUTs(odt_info,
1740                                 lmt_info,
1741                                 shaper_name,
1742                                 aces_CTL_directory,
1743                                 lut_directory,
1744                                 lut_resolution_1d,
1745                                 lut_resolution_3d,
1746                                 cleanup)
1747
1748     # Create the config using the generated LUTs
1749     print('Creating generic config')
1750     config = create_config(config_data)
1751     print('\n\n\n')
1752
1753     # Write the config to disk
1754     write_config(config, '%s/config.ocio' % config_directory)
1755
1756     # Create a config that will work well with Nuke using the previously
1757     # generated LUTs.
1758     print('Creating Nuke-specific config')
1759     nuke_config = create_config(config_data, nuke=True)
1760     print('\n\n\n')
1761
1762     # Write the config to disk
1763     write_config(nuke_config, '%s/nuke_config.ocio' % config_directory)
1764
1765     # Bake secondary LUTs using the config
1766     if bake_secondary_LUTs:
1767         generate_baked_LUTs(odt_info,
1768                             shaper_name,
1769                             '%s/baked' % config_directory,
1770                             '%s/config.ocio' % config_directory,
1771                             lut_resolution_1d,
1772                             lut_resolution_3d,
1773                             lut_resolution_1d)
1774
1775     return True
1776
1777
1778 def main():
1779     """
1780     Object description.
1781
1782     Parameters
1783     ----------
1784     parameter : type
1785         Parameter description.
1786
1787     Returns
1788     -------
1789     type
1790          Return value description.
1791     """
1792
1793     import optparse
1794
1795     p = optparse.OptionParser(description='An OCIO config generation script',
1796                               prog='createACESConfig',
1797                               version='createACESConfig 0.1',
1798                               usage='%prog [options]')
1799     p.add_option('--acesCTLDir', '-a', default=os.environ.get(
1800         'ACES_OCIO_CTL_DIRECTORY', None))
1801     p.add_option('--configDir', '-c', default=os.environ.get(
1802         'ACES_OCIO_CONFIGURATION_DIRECTORY', None))
1803     p.add_option('--lutResolution1d', default=4096)
1804     p.add_option('--lutResolution3d', default=64)
1805     p.add_option('--dontBakeSecondaryLUTs', action='store_true')
1806     p.add_option('--keepTempImages', action='store_true')
1807
1808     options, arguments = p.parse_args()
1809
1810     #
1811     # Get options
1812     #
1813     aces_CTL_directory = options.acesCTLDir
1814     config_directory = options.configDir
1815     lut_resolution_1d = int(options.lutResolution1d)
1816     lut_resolution_3d = int(options.lutResolution3d)
1817     bake_secondary_LUTs = not (options.dontBakeSecondaryLUTs)
1818     cleanup_temp_images = not (options.keepTempImages)
1819
1820     try:
1821         args_start = sys.argv.index('--') + 1
1822         args = sys.argv[args_start:]
1823     except:
1824         args_start = len(sys.argv) + 1
1825         args = []
1826
1827     print('command line : \n%s\n' % ' '.join(sys.argv))
1828
1829     # TODO: Use assertion and mention environment variables.
1830     if not aces_CTL_directory:
1831         print('process: No ACES CTL directory specified')
1832         return
1833     if not config_directory:
1834         print('process: No configuration directory specified')
1835         return
1836     #
1837     # Generate the configuration
1838     #
1839     return create_ACES_config(aces_CTL_directory,
1840                               config_directory,
1841                               lut_resolution_1d,
1842                               lut_resolution_3d,
1843                               bake_secondary_LUTs,
1844                               cleanup_temp_images)
1845
1846
1847 if __name__ == '__main__':
1848     main()