..
  SPDX-License-Identifier: BSD-3-Clause
  Copyright Contributors to the OpenEXR Project.

.. _porting:

OpenEXR/Imath 2.x to 3.x Porting Guide
######################################

This porting guide outlines the several areas where switching from OpenEXR
2.x to OpenEXR 3.x + Imath 3.x will require source code or build changes of
downstream software.

In each case, we will often explain both how to change if you are expecting
3.x only hereafter, or usually a more complex accommodation if you want to
keep compatibility with both 2.x and 3.x.

OpenEXR and Imath Are Different Packages
========================================

If your use of OpenEXR was only for the sake of using the math classes and
utilities, maybe you were unhappy that you needed to download and build the
full OpenEXR dependency. You are in luck -- now Imath is a separate, very
lightweight open source package. You can use Imath functionality without
needing any of OpenEXR, which as of 3.x only includes the parts you need to
read and write OpenEXR image files.

The parts of "IlmBase" that were ``Imath`` and ``half`` are now repackaged
as the ``Imath`` library. The ``IlmThread`` and ``Iex`` libraries have been
folded into the OpenEXR package, since they were were not necessary to
the rest of Imath.

When building OpenEXR 3.x, note that if Imath 3.x library is not found
already installed at build time, it will be automatically downloaded and
built as part of the OpenEXR build.

Background
==========

Why is this happening? Here is the relevant history.

The OpenEXR project has historically consisted of four separate subprojects:

* ``OpenEXR`` - the Imf image format
* ``IlmBase`` - supporting utilities (Imath, Half, Iex, IlmThread)
* ``PyIlmBase`` - python bindings for the IlmBase libraries
* ``OpenEXR_Viewers`` - code for an example EXR image viewer 

Prior to the 2.4 release in 2019, OpenEXR relied primarily on the Gnu
autotools build system and was released as four separate tarballs
(ilmbase, pyilmbase, openexr, openexr_viewers) that were constructed
via the Gnu tools. This gave direct access to the "IlmBase" libraries
independent of the OpenEXR format library. The project also included
CMake files but CMake support was incomplete.

With the adoption of OpenEXR by the Academy Software Foundation in
2019, the technical steering committee made several key changes:

1. Drop support for autotools in favor of CMake. A significant portion
   of the OpenEXR user base uses Windows, which the Gnu autotools does
   not support.  Supporting two build systems is a maintenance burden
   that the TSC opted to avoid. We now assume that all modern users of
   OpenEXR can reasonably be expected to rely on CMake.

2. Rely on GitHub's automatic release packaging mechanism. This
   packages the entire contents of package in a single
   tarball. Separate tarballs are no longer generated by the Gnu
   autotools setup.

3. Deprecate the OpenEXR_Viewers code. It was impossibly out of date
   and of little modern value.

Thus, with the 2.4 release, the "IlmBase" libraries are no longer
distributed in a form that is readily separable from the rest of
OpenEXR. The build and installation process for the overall OpenEXR
project is complicated by the fact it consists of four separate
projects, which added significant complexity to the CMake setup.

Because Imath is generally useful to the community, the TSC decided to
simplify the configuration by separating Imath into its own independent
project, maintained and released independently of OpenEXR, and
introducing it as a new external dependency of OpenEXR.

To further simplify matters, the new Imath library includes the half
data type directly, rather than maintaining it in a separate
library. Also, the community at large has a strong desire for simple
vector/matrix utilities that are unencumbered by Iex, the IlmBase
library that provides higher-level exception classes, and even
further, a clear delineation between functionality that (1) relies on
exception handlings and (2) is free from exceptions. As a result,
support for Iex has been removed from Imath, and the Iex library is
now packaged as a component of OpenEXR.

The Imath python bindings are a part of Imath as a configuration
option, although support is off by default to simplify the build process
for most users.

New Library Names and Repository Structures
===========================================

The new repositories place all source code under the ``src`` top-level
subdirectory.

Imath:
------

.. code-block::

    src
    ├── Imath
    ├── ImathTest
    └── python
        ├── config
        ├── PyImath
        ├── PyImathNumpy
        ├── PyImathTest
        ├── PyImathNumpyTest
        └── PyImathSpeedTest


OpenEXR:
--------

The ``IlmImf`` library has been renamed ``OpenEXR``. No header files have
changed names, only their locations in the repo have changes.

.. code-block::

    src
    ├── bin
    │   ├── exr2aces
    │   ├── exrbuild
    │   ├── exrcheck
    │   ├── exrenvmap
    │   ├── exrheader
    │   ├── exrmakepreview
    │   ├── exrmaketiled
    │   ├── exrmultipart
    │   ├── exrmultiview
    │   └── exrstdattr
    ├── lib
    │   ├── Iex
    │   ├── IexMath
    │   ├── IlmThread
    │   ├── OpenEXR
    │   └── OpenEXRUtil
    ├── examples
    └── test
        ├── IexTest
        ├── OpenEXRTest
        ├── OpenEXRUtilTest
        └── OpenEXRFuzzTest


Finding and Using OpenEXR and Imath CMake Configs
=================================================

OpenEXR/Imath 3.x Only
----------------------

If you are *only* concerned with OpenEXR/Imath 3.x going forward, this is
the recommended way to find the libraries in a downstream project that uses
the CMake build system:

.. code-block::

    find_package(Imath CONFIG)
    find_package(OpenEXR CONFIG)

Note that the second line may be omitted if you only need the Imath
portions.

And then your project can reference the imported targets like this:

.. code-block::

    target_link_libraries (my_target
        PRIVATE
            OpenEXR::OpenEXR
            Imath::Imath
            Imath::Half
        )

You only need the parts you use, so for example, if you only need Half and
Imath, you can omit the OpenEXR target. Also note that in our example above,
we have used the ``PRIVATE`` label, but you should specify them as ``PUBLIC`` if
you are exposing those classes in your own package's public interface.


Accommodating OpenEXR/Imath 3.x or OpenEXR 2.x
----------------------------------------------

On the other hand, to accommodate both 2.x and 3.x, it's admittedly
inconvenient because the packages and the import targets have changed their
names.  We have found the following idioms to work:

Finding either/both packages:

.. code-block::

    # First, try to find just the right config files
    find_package(Imath CONFIG)
    if (NOT TARGET Imath::Imath)
        # Couldn't find Imath::Imath, maybe it's older and has IlmBase?
        find_package(IlmBase CONFIG)
    endif ()
    find_package(OpenEXR CONFIG)

To link against them, we use CMake generator expressions so that we can
reference *both* sets of targets, but it will only use the ones
corresponding to the package version that was found.

.. code-block::

    target_link_libraries (my_target
        PRIVATE
            # For OpenEXR/Imath 3.x:
              $<$<TARGET_EXISTS:OpenEXR::OpenEXR>:OpenEXR::OpenEXR>
              $<$<TARGET_EXISTS:Imath::Imath>:Imath::Imath>
              $<$<TARGET_EXISTS:Imath::Half>:Imath::Half>
            # For OpenEXR 2.4/2.5:
              $<$<TARGET_EXISTS:OpenEXR::IlmImf>:OpenEXR::IlmImf>
              $<$<TARGET_EXISTS:IlmBase::Imath>:IlmBase::Imath>
              $<$<TARGET_EXISTS:IlmBase::Half>:IlmBase::Half>
              $<$<TARGET_EXISTS:IlmBase::IlmThread>:IlmBase::IlmThread>
              $<$<TARGET_EXISTS:IlmBase::Iex>:IlmBase::Iex>
        )

Again, you can eliminate the references to any of the individual libraries
that you don't actually need for your application.

Simultaneous Static/Shared Build
--------------------------------

The OpenEXR 2.x CMake configuration had options to simultaneously
build both shared and statically linked libraries. This has been
deprecated. A CMake configuration setting specifies whether to build
static or shared, but if you want both, you will need to run cmake and
build twice.

Simultaneous Python 2/3 Build
-----------------------------

The PyIlmBase 2.x CMake configuration had options to simultaneously
build both python2 and python3 bindings. This has been deprecated.
A CMake configuration setting specifies whether to build for
python 2 or python 3, but if you want both, you will need to run
cmake and build twice.

Imath Include Files Are in a Different Subdirectory
===================================================

Imath 3.0 will copy its headers to some ``include/Imath`` subdirectory
instead of the old ``include/OpenEXR``.

OpenEXR/Imath 3.x Only
----------------------

If you know that you are only using Imath 3.x, then just change any
include directions, like this:

.. code-block::

    #include <OpenEXR/ImathVec.h>
    #include <OpenEXR/half.h>

to the new locations:

.. code-block::

    #include <Imath/ImathVec.h>
    #include <Imath/half.h>

Accommodating OpenEXR/Imath 3.x or OpenEXR 2.x
----------------------------------------------

If you want your software to be able to build against either OpenEXR 2.x or
3.x (depending on which dependency is available at build time), we recommend
using a more complicated idiom:

.. code-block::

    // The version can reliably be found in this header file from OpenEXR,
    // for both 2.x and 3.x:
    #include <OpenEXR/OpenEXRConfig.h>
    #define COMBINED_OPENEXR_VERSION ((10000*OPENEXR_VERSION_MAJOR) + \
                                      (100*OPENEXR_VERSION_MINOR) + \
                                      OPENEXR_VERSION_PATCH)

    // There's just no easy way to have an ``#include`` that works in both
    // cases, so we use the version to switch which set of include files we
    // use.
    #if COMBINED_OPENEXR_VERSION >= 20599 /* 2.5.99: pre-3.0 */
    #   include <Imath/ImathVec.h>
    #   include <Imath/half.h>
    #else
        // OpenEXR 2.x, use the old locations
    #   include <OpenEXR/ImathVec.h>
    #   include <OpenEXR/half.h>
    #endif

Include Files Include Fewer Other Headers
=========================================

Extraneous ``#include`` statements have been removed from some header
files, which can lead to compile failures in application code that
previously included certain headers indirectly.

For example, the Imath header files no longer include ``float.h``, so
application code that references symbols such as ``FLT_MAX`` may need
to add an explicit ``#include <float.h>`` or equivalent.

If your application code reports compile errors due to undefined or
incompletely-defined Imath or OpenEXR data types, locate the Imath or
OpenEXR header file that defines the type and include it explicitly.

Symbols Are Hidden by Default
=============================

To reduce library size and make linkage behavior similar across
platforms, Imath and OpenEXR now build with directives that make
symbol visibility hidden by default, with specific externally-visible
symbols explicitly marked for export. See the :doc:`SymbolVisibility`
and the appropriate ``*Export.h`` header file for more details.

Imath Now Uses Standard C++ Exceptions and ``noexcept``
=======================================================

In OpenEXR 2.x, the Imath functions that threw exceptions used to throw
various Iex varieties.

In Imath 3.x, these functions just throw ``std::exception`` varieties that
correspond to the failure (e.g., ``std::invalid_argument``,
``std::domain_error``, etc.). For that reason, all of the Iex exceptions are
now only part of the OpenEXR library (where they are still used in the same
manner they were for OpenEXR 2.x).

Imath 3.x has very few functions that throw exceptions. Each is clearly
marked as such, and each has a version that does not throw exceptions (so
that it may be used from code where exceptions are avoided). The functions
that do not throw exceptions are now marked ``noexcept``.

Some Headers and Classes Have Been Removed from Imath 3.x
=========================================================

* The ``Math<T>`` class (and ``ImathMath.h`` header file) are
  deprecated. All of the ``Math<T>`` functionality is subsumed by C++11
  ``std::`` math functions. For example, calls to
  ``Imath::Math<T>::abs(x)`` should be replaced with ``std::abs(x)``.

* The ``Limits<T>`` class (and the ``ImathLimits.h`` and
  ``ImathHalfLimits.h`` headers) have been removed entirely. All uses of
  ``Limits<>`` should be replaced with the appropriate
  ``std::numeric_limits<>`` method call. The Imath-specific versions
  predated C++11, and were not only redundant in a C++11 world, but
  also potentially confusing because some of their functions behaved
  quite differently than the ``std::numeric_limits`` method with the
  same name. We are following the precept that if C++11 does something
  in a standard way, we should not define our own equivalent function
  (and especially not define it in a way that doesn't match the
  standard behavior).

* ``Vec<T>::normalize()`` and ``length()`` methods, for integer ``T`` types,
  have been removed. Also the standalone ``project()`` and
  ``orthogonal()`` functions are no longer defined for vectors made of
  integer elements. These all had behavior that was hard to understand
  and probably useless. They still work as expected for vectors of
  floating-point types.

* The ``Int64`` and ``SInt64`` types are deprecated in favor of the
  now-standard ``int64_t`` and ``uint64_t``.

File/Class-specific Changes
===========================

``half`` in ``half.h``
----------------------

* The half type is now in the ``Imath`` namespace, but a compile-time
  option puts it in the global namespace, except when compiling for
  CUDA, in which case the 'half' type refers to the CUDA type:

.. code-block::

      #ifndef __CUDACC__
      using half = IMATH_INTERNAL_NAMESPACE::half;
      #else
      #include <cuda_fp16.h>
      #endif

  If you desire to use Imath::half inside a CUDA kernel, you can refer
  to it via the namespace, or define ``CUDA_NO_HALF`` to avoid the CUDA
  type altogether.

* ``HALF_MIN`` has changed value. It is now the smallest **normalized**
   positive value, returned by ``std::numeric_limits<half>::min()``.

* New constructor from a bit pattern:

.. code-block::

      enum FromBitsTag
      {
          FromBits
      };

      constexpr half(FromBitsTag, unsigned short bits) noexcept;

``Imath::Box<T>`` in ``ImathBox.h``
-----------------------------------

* ``baseTypeMin()`` is replaced with ``baseTypeLowest()``

``Color3<T>``, ``Color4<T>`` in ``ImathColor.h``
------------------------------------------------

* ``baseTypeMin()`` is replaced with ``baseTypeLowest()``

``Imath::Frustum<T>`` in ``ImathFrustum.h``
-------------------------------------------

Akin to the ``Vec`` classes, there are now separate API calls for
throwing and non-throwing functions:

These functions previously threw exceptions but now do not throw and
are marked ``noexcept``:

* ``Frustum<T>::projectionMatrix() noexcept``

* ``Frustum<T>::aspect() noexcept``

* ``Frustum<T>::set() noexcept``

* ``Frustum<T>::projectPointToScreen() noexcept``

* ``Frustum<T>::ZToDepth() noexcept``

* ``Frustum<T>::DepthToZ() noexcept``

* ``Frustum<T>::screenRadius() noexcept``

* ``Frustum<T>::localToScreen() noexcept``

These functions throw ``std::domain_error`` exceptions when the
associated frustum is degenerate:

* ``Frustum<T>::projectionMatrixExc()``

* ``Frustum<T>::aspectExc()``

* ``Frustum<T>::setExc()``

* ``Frustum<T>::projectPointToScreenExc()``

* ``Frustum<T>::ZToDepthExc()``

* ``Frustum<T>::DepthToZExc()``

* ``Frustum<T>::screenRadiusExc()``

* ``Frustum<T>::localToScreenExc()``

``Imath::Interval<T>`` in ``ImathInterval.h``
---------------------------------------------

New methods/functions: 

* ``Interval<T>::operator !=``

* ``Interval<T>::makeInfinite()``

* ``Interval<T>isInfinite()``

* ``operator<< (std::ostream& s, const Interval<T>&)``

``ImathMatrixAlgo.h``
---------------------

* ``checkForZeroScaleInRow()`` and ``extractAndRemoveScalingAndShear()``
   throw ``std::domain_error`` exceptions instead of ``Iex::ZeroScale``

``Matrix22<T>``, ``Matrix33<T>``, ``Matrix44<T>`` in ``ImathMatrix.h``
----------------------------------------------------------------------

* ``baseTypeMin()`` is replaced with ``baseTypeLowest()``

* ``invert(bool singExc = false)`` is replace by:

  - ``invert() noexcept``

  - ``invert(bool)`` which optionally throws an ``std::invalid_argument``
    exception.

* ``inverse(bool singExc = false)`` is replace by:

  - ``inverse() noexcept``

  - ``inverse(bool)`` which optionally throws an ``std::invalid_argument``
    exception.

* ``gjInvert(bool singExc = false)`` is replace by:

  - ``gjInvert()`` noexcept

  - ``gjInvert(bool)`` which optionally throws an
    ``std::invalid_argument`` exception.

* ``gJinverse(bool singExc = false)`` is replace by:

  - ``gjInverse()`` noexcept

  - ``gjInverse(bool)`` which optionally throws an
    ``std::invalid_argument`` exception.

New functions:

* ``operator<< (std::ostream& s, const Matrix22<T>&)``

* ``operator<< (std::ostream& s, const Matrix33<T>&)``

* ``operator<< (std::ostream& s, const Matrix44<T>&)``

Other changes:

* Initialization loops unrolled for efficiency

* inline added where appropriate

``ImathRoots.h``
----------------

* When compiling for CUDA, the ``complex`` type comes from ``thrust``
  rather than ``std``

``Shear6`` in ``ImathShear.h``
------------------------------

* ``baseTypeMin()`` is replaced with ``baseTypeLowest()``

``ImathVecAlgo.h``
------------------

The following functions are no longer defined for integer-based
vectors, because such behavior is not clearly defined:

* ``project (const Vec& s, const Vec& t)``

* ``orgthogonal (const Vec& s, const Vec& t)``

* ``reflect (const Vec& s, const Vec& t)``

``Vec2<T>``, ``Vec3<T>``, ``Vec4<T>`` in ``ImathVec.h``
-------------------------------------------------------

* ``baseTypeMin()`` is replaced with ``baseTypeLowest()``

* The following methods are removed (via ``= delete``) for integer-based
  vectors because the behavior is not clearly defined and thus prone
  to confusion:

  - ``length()`` - although the length is indeed defined, its proper value
    is floating point and can thus not be represented by the 'T'
    return type.

  - ``normalize()``

  - ``normalizeExc()``

  - ``normalizeNonNull()``

  - ``normalized()``

  - ``normalizedExc()``

  - ``normalizedNonNull()``
 
* Interoperability Constructors: The Vec and Matrix classes now have
  constructors that take as an argument any data object of similar
  size and layout.

Imath Python Changes
====================

In general, the changes in Imath at the C++ level are reflected in the
python bindings. In particular:

* The following methods are removed for integer-based
  vector and matrix objects and arrays:

  - ``length()``
  - ``normalize()``
  - ``normalizeExc()``
  - ``normalizeNonNull()``
  - ``normalized()``
  - ``normalizedExc()``
  - ``normalizedNonNull()``

* ``baseTypeMin()`` is replaced with ``baseTypeLowest()`` for:

   - ``Vec2``, ``Vec3``, ``Vec4``
   - ``Color3``, ``Color4``
   - ``Matrix22``, ``Matrix33``, ``Matrix44``
   - ``Box``
   - ``Shear6``

