swf2ass/src/ColorTransform.php

68 lines
3.1 KiB
PHP

<?php
namespace swf2ass;
class ColorTransform {
public Color $mult;
public Color $add;
public function __construct(Color $mult, Color $add) {
$this->mult = $mult;
$this->add = $add;
}
public static function identity(): ColorTransform {
return new ColorTransform(new Color(256, 256, 256, 256), new Color(0, 0, 0));
}
public function applyToStyleContainer(StyleContainer $styles): StyleContainer {
if ($styles->original_color1 instanceof Color) {
$styles->color1 = $styles->original_color1->applyTransform($this);
}
if ($styles->original_color3 instanceof Color) {
$styles->color3 = $styles->original_color3->applyTransform($this);
}
return $styles;
}
public function applyMultiplyToColor(Color $color): Color {
return new Color(max(0, min(($this->mult->r * $color->r) / 256, 255)), max(0, min(($this->mult->g * $color->g) / 256, 255)), max(0, min(($this->mult->b * $color->b) / 256, 255)), max(0, min(($this->mult->alpha * $color->alpha) / 256, 255)),);
}
public function applyAdditionToColor(Color $color): Color {
return new Color(max(0, min($this->add->r + $color->r, 255)), max(0, min($this->add->g + $color->g, 255)), max(0, min($this->add->b + $color->b, 255)), max(0, min($this->add->alpha + $color->alpha, 255)),);
}
public function applyToColor(Color $color): Color {
return new Color(max(0, min((($this->mult->r * $color->r) / 256) + $this->add->r, 255)), max(0, min((($this->mult->g * $color->g) / 256) + $this->add->g, 255)), max(0, min((($this->mult->b * $color->b) / 256) + $this->add->b, 255)), max(0, min((($this->mult->alpha * $color->alpha) / 256) + $this->add->alpha, 255)),);
}
public function combine(ColorTransform $transform) {
//TODO: maybe these get altered all at once?
return new ColorTransform($this->applyMultiplyToColor($transform->mult), $this->applyAdditionToColor($transform->add));
}
public function equals(ColorTransform $other, $epsilon = Constants::EPSILON): bool {
return ($this->mult === $other or ($this->mult !== null and $this->mult->equals($other->mult))) and ($this->add === $other or ($this->add !== null and $this->add->equals($other->add)));
}
public static function fromXML(\DOMElement $element): ColorTransform {
$add = new Color(0, 0, 0, 0);
$mult = new Color(256, 256, 256, 256);
if ($element->hasAttribute("factorRed")) {
$mult->r = (int)$element->getAttribute("factorRed");
$mult->g = (int)$element->getAttribute("factorGreen");
$mult->b = (int)$element->getAttribute("factorBlue");
$mult->alpha = (int)$element->getAttribute("factorAlpha");
}
if ($element->hasAttribute("offsetRed")) {
$add->r = (int)$element->getAttribute("offsetRed");
$add->g = (int)$element->getAttribute("offsetGreen");
$add->b = (int)$element->getAttribute("offsetBlue");
$add->alpha = (int)$element->getAttribute("offsetAlpha");
}
return new ColorTransform($mult, $add);
}
}