001/*
002Copyright 2006 Jerry Huxtable
003
004Licensed under the Apache License, Version 2.0 (the "License");
005you may not use this file except in compliance with the License.
006You may obtain a copy of the License at
007
008   http://www.apache.org/licenses/LICENSE-2.0
009
010Unless required by applicable law or agreed to in writing, software
011distributed under the License is distributed on an "AS IS" BASIS,
012WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013See the License for the specific language governing permissions and
014limitations under the License.
015*/
016
017package com.jhlabs.composite;
018
019import java.awt.*;
020import java.awt.image.*;
021
022public final class DifferenceComposite extends RGBComposite {
023
024        public DifferenceComposite( float alpha ) {
025        super( alpha );
026        }
027
028        public CompositeContext createContext( ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints ) {
029                return new Context( extraAlpha, srcColorModel, dstColorModel );
030        }
031
032    static class Context extends RGBCompositeContext {
033        public Context( float alpha, ColorModel srcColorModel, ColorModel dstColorModel ) {
034            super( alpha, srcColorModel, dstColorModel );
035        }
036
037        public void composeRGB( int[] src, int[] dst, float alpha ) {
038            int w = src.length;
039
040            for ( int i = 0; i < w; i += 4 ) {
041                int sr = src[i];
042                int dir = dst[i];
043                int sg = src[i+1];
044                int dig = dst[i+1];
045                int sb = src[i+2];
046                int dib = dst[i+2];
047                int sa = src[i+3];
048                int dia = dst[i+3];
049                int dor, dog, dob;
050
051                dor = dir - sr;
052                if ( dor < 0 )
053                    dor = -dor;
054                dog = dig - sg;
055                if ( dog < 0 )
056                    dog = -dog;
057                dob = dib - sb;
058                if ( dob < 0 )
059                    dob = -dob;
060
061                float a = alpha*sa/255f;
062                float ac = 1-a;
063
064                dst[i] = (int)(a*dor + ac*dir);
065                dst[i+1] = (int)(a*dog + ac*dig);
066                dst[i+2] = (int)(a*dob + ac*dib);
067                dst[i+3] = (int)(sa*alpha + dia*ac);
068            }
069        }
070    }
071
072}