/* JFlexiPix - Java implementation of FlexiPix output library
 *
 * Copyright 2010-2011 Stefan Schuermans <stefan schuermans info>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package org.blinkenarea.JFlexiPix;

/**
 * FlexiPix mapping information
 *
 * values of channels are mapped according to following formula:
 * <display value> := <base> + <factor> * <original value> ^ (1 / <gamma>)
 */
class Mapping
{
  /// constructor
  Mapping()
  {
    // default mapping information
    set(0.0, 1.0, 1.0);
  }

  /**
   * @brief set mapping information
   * @param[in] base base constant for brightness correction
   * @param[in] factor factor for contrast modification
   * @param[in] gamma gamma correction factor, must be > 0.0
   */
  void set(double base, double factor, double gamma)
  {
    double gamma_1;
    int v;

    // save mapping parameters
    m_base   = base;
    m_factor = factor;
    m_gamma  = gamma;

    // allocate mapping table
    m_table = new byte [256];

    // fill mapping table
    gamma_1 = 1.0 / m_gamma;
    for (v = 0; v < 256; ++v) {
      double val = m_base + m_factor * Math.pow((double)v / 255.0, gamma_1);
      if (val < 0.0)
        m_table[v] = (byte)0;
      else if (val > 1.0)
        m_table[v] = (byte)255;
      else
        m_table[v] = (byte)(val * 255.0 + 0.5);
    }
  }

  double  m_base;   ///< base constant for brightness correction
  double  m_factor; ///< factor for contrast modification
  double  m_gamma;  ///< gamma correction factor, must be > 0.0
  byte [] m_table;  /**< precalculated mapping table,
                     *   index: source image value
                     *   value: display value */
}

