#include #include "DYUniforms.h" #include "DYToolGPU.h" #include "SpiderCore/DYColorMath.h" using namespace metal; // The linked, versioned AIR helper owns color arithmetic only. Its source is in // tools/kernels; production builds never read the reference application. extern "C" half4 dy_grade(half4 sample, float2 uv, texture2d source, texture3d preLUT, texture3d look1, texture3d look2, texture3d look3, texture3d look4, texture3d look5, texture3d hslMixer, texture3d whiteBalance, texture3d colorGrading, constant DYUniforms& uniforms, constant float& sceneLevel); extern "C" half4 dy_gradeMasked(half4 sample, float2 uv, texture2d source, texture3d preLUT, texture3d look1, texture3d look2, texture3d look3, texture3d look4, texture3d look5, texture3d hslMixer, texture3d whiteBalance, texture3d colorGrading, constant DYUniforms& uniforms, constant float& sceneLevel,float w0,float w1,float w2,float w3,float w4,float w5,float w6,float w7,float w8,float w9,float w10,float w11); extern "C" half4 dy_gradeSegment(half4 sample, float2 uv, texture2d source, texture3d preLUT, texture3d look1, texture3d look2, texture3d look3, texture3d look4, texture3d look5, texture3d hslMixer, texture3d whiteBalance, texture3d colorGrading, constant DYUniforms& uniforms, constant float& sceneLevel,float w0,float w1,float w2,float w3,float w4,float w5,float w6,float w7,float w8,float w9,float w10,float w11,uint stageFirst,uint stageLast,float3 skinReference,float3 originalReference); struct DYRaster { float4 position [[position]]; float2 uv; }; vertex DYRaster dyVertex(uint vertexID [[vertex_id]], constant DYVertex2D* vertices [[buffer(0)]], constant uint2& viewportSize [[buffer(1)]]) { DYRaster result; result.position = float4(vertices[vertexID].position / (float2(viewportSize) * 0.5f), 0.0f, 1.0f); result.uv = vertices[vertexID].textureCoordinate; return result; } fragment half4 dyFragment(DYRaster in [[stage_in]], texture2d source [[texture(0)]], texture3d preLUT [[texture(1)]], texture3d look1 [[texture(2)]], texture3d look2 [[texture(3)]], texture3d look3 [[texture(4)]], texture3d look4 [[texture(5)]], texture3d look5 [[texture(6)]], texture3d hslMixer [[texture(7)]], texture3d whiteBalance [[texture(8)]], texture3d colorGrading [[texture(9)]], constant DYUniforms& uniforms [[buffer(0)]], constant float& sceneLevel [[buffer(1)]], constant DYRenderOptions& options [[buffer(2)]], constant DYUniforms& colorUniforms [[buffer(3)]], device const float* spiderSamples [[buffer(4)]], constant int2& spiderSize [[buffer(5)]]) { constexpr sampler sampleFilter(coord::normalized, address::clamp_to_edge, filter::linear); half4 sample = source.sample(sampleFilter, in.uv); if (!(sample.a > half(0.0))) return half4(0.0h); half4 result = dy_grade(sample, in.uv, source, preLUT, look1, look2, look3, look4, look5, hslMixer, whiteBalance, colorGrading, uniforms, sceneLevel); if(options.blackWhiteMix>0.0f && options.blackWhiteMix<1.0f) { half4 color=dy_grade(sample,in.uv,source,preLUT,look1,look2,look3,look4,look5,hslMixer,whiteBalance,colorGrading,colorUniforms,sceneLevel); result.rgb=mix(color.rgb,result.rgb,half(options.blackWhiteMix)); } if(spiderSize.x>0 && uniforms.spiderSectionEnabled>.5f && uniforms.spiderMix>0.0f){ float3 color=float3(result.rgb);float3 warped=dyVariableSpider(color,spiderSize.x,spiderSize.y,spiderSamples); result.rgb=half3(dyLimit(mix(color,warped,uniforms.spiderMix))); } result.a = sample.a; if (options.outputPremultiplied) result.rgb *= result.a; return result; } inline float dyToolMaskSoftStep(float low,float high,float value){if(high<=low)return value>=high?1:0;return dySmooth(low,high,value);} inline float dyToolMaskRangeWeight(float value,thread const DYMaskRange& range){ float low=value>=range.low?1:dyToolMaskSoftStep(range.low-range.softLow,range.low,value); float high=value<=range.high?1:1-dyToolMaskSoftStep(range.high,range.high+range.softHigh,value); return low*high; } inline float dyToolMaskLeveledCoverage(float raw,thread const DYMaskParameters& p){ float a=dyClamp((raw-p.inputBlack)/(p.inputWhite-p.inputBlack),0,1); if(p.inputGamma!=1&&a>0&&a<1)a=pow(a,1/p.inputGamma); return p.outputBlack+(p.outputWhite-p.outputBlack)*a; } inline float dyToolMaskFinalCoverage(float a,thread const DYMaskParameters& p){ if(p.flags&DYMaskInvert)a=1-a; return dyClamp(a*p.strength,0,1); } inline float dyToolMaskLevels(float raw,thread const DYMaskParameters& p){return dyToolMaskFinalCoverage(dyToolMaskLeveledCoverage(raw,p),p);} inline float dyToolMaskHSLWeight(float3 source,thread const DYMaskParameters& p){ float3 c=dyLimit(source);float lo=c.xc.y?(c.x>c.z?c.x:c.z):(c.y>c.z?c.y:c.z); // Same signed/HDR interval convention as the quick HSL tools. This is code // RGB selection; use LumaKey levels when absolute HDR brightness is needed. float base=lo<0?lo:0,scale=hi-base;if(scale<1)scale=1; float3 hsl=dyRGBHSL((c-float3{base,base,base})/scale);float weight=1; if(p.flags&DYMaskHueEnabled){ float distance=dyHueDistance(hsl.x,p.hueCenterTurns),outer=p.hueCoreHalfWidth+p.hueSoftWidth;if(outer>.5f)outer=.5f; float hue=p.hueCoreHalfWidth>=.5f||distance<=p.hueCoreHalfWidth?1:1-dyToolMaskSoftStep(p.hueCoreHalfWidth,outer,distance); float chroma=(hi-lo)/scale;weight*=hue*dyToolMaskSoftStep(p.neutralChromaLow,p.neutralChromaHigh,chroma); } if(p.flags&DYMaskSaturationEnabled)weight*=dyToolMaskRangeWeight(hsl.y,p.saturationRange); if(p.flags&DYMaskLightnessEnabled)weight*=dyToolMaskRangeWeight(hsl.z,p.lightnessRange); return weight; } inline float dyToolMaskShapeWeight(float x,float y,thread const DYMaskParameters& p,thread const DYMaskPath& path){ float dx=(x-p.centerX)*p.imageAspect,dy=y-p.centerY,ca=cos(p.angle),sa=sin(p.angle); float px=dx*ca+dy*sa,py=-dx*sa+dy*ca; if(p.kind==DYMaskLinearGradient){ if(p.gradientWidth==0)return px>=0?1:0; return dyToolMaskSoftStep(0,1,.5f+px/(p.gradientWidth>1e-12f?p.gradientWidth:1e-12f)); } float physicalWidth=p.width*p.imageAspect,physicalHeight=p.height;if(physicalWidth<1e-12f)physicalWidth=1e-12f;if(physicalHeight<1e-12f)physicalHeight=1e-12f; if(p.kind==DYMaskEllipse){float u=px/(physicalWidth*.5f),v=py/(physicalHeight*.5f),r=sqrt(u*u+v*v);if(p.feather==0)return r<=1?1:0;if(p.version==2&&(p.flags&DYMaskFeatherOutsideFlag))return 1-dyToolMaskSoftStep(1,1+p.feather,r);return 1-dyToolMaskSoftStep(1-p.feather,1,r);} float shorter=physicalWidth=0&&b>=0?1:0;return dyToolMaskSoftStep(-p.feather*.5f*shorter,0,a256)return 0; float u=px/physicalWidth,v=py/physicalHeight,sx=physicalWidth/shorter,sy=physicalHeight/shorter,distance2=1e10f;bool inside=false; for(int i=0,j=path.count-1;iv)!=(by>v))if(u<(bx-ax)*(v-ay)/(by-ay)+ax)inside=!inside; float ex=(bx-ax)*sx,ey=(by-ay)*sy,xx=(u-ax)*sx,yy=(v-ay)*sy,den=ex*ex+ey*ey,t=den>1e-12f?dyClamp((xx*ex+yy*ey)/den,0,1):0; xx-=t*ex;yy-=t*ey;float d=xx*xx+yy*yy;if(dDYMaskLumaKey)return 0; float raw=dyToolMaskRawCoverage(x,y,source,p,path); return dyToolMaskLevels(raw,p); } inline float dyToolMask(float x,float y,float3 source,device const DYResolvedMask& value){DYResolvedMask local=value;return dyToolMaskOperator(x,y,source,local.parameters,local.path);} inline float3 dyToolEncode(float3 linear){return select(1.055f*pow(max(linear,float3(0)),float3(1.f/2.4f))-.055f,linear*12.92f,linear<=.0031308f);} inline float3 dyToolDecode(float3 encoded){return select(pow(max((encoded+.055f)/1.055f,float3(0)),float3(2.4f)),encoded/12.92f,encoded<=.04045f);} inline float dyToolCoverage(float2 uv,float3 source,device const DYToolMaskEntry* masks,constant DYToolMaskHeader& h,int section){ float x=h.offsetX+uv.x*h.scaleX,y=h.offsetY+uv.y*h.scaleY;float coverage=1;bool found=false; for(uint i=0;i source [[texture(0)]], texture3d preLUT [[texture(1)]], texture3d look1 [[texture(2)]], texture3d look2 [[texture(3)]], texture3d look3 [[texture(4)]], texture3d look4 [[texture(5)]], texture3d look5 [[texture(6)]], texture3d hslMixer [[texture(7)]], texture3d whiteBalance [[texture(8)]], texture3d colorGrading [[texture(9)]], constant DYUniforms& uniforms [[buffer(0)]], constant float& sceneLevel [[buffer(1)]], constant DYRenderOptions& options [[buffer(2)]], constant DYUniforms& colorUniforms [[buffer(3)]], device const float* spiderSamples [[buffer(4)]], constant int2& spiderSize [[buffer(5)]], device const DYToolMaskEntry* masks [[buffer(6)]], constant DYToolMaskHeader& maskHeader [[buffer(7)]]) { constexpr sampler sampleFilter(coord::normalized, address::clamp_to_edge, filter::linear); half4 sample = source.sample(sampleFilter, in.uv); if (!(sample.a > half(0.0))) return half4(0.0h); float weights[12];float3 encoded=dyToolEncode(float3(sample.rgb)); for(int i=0;i<12;i++)weights[i]=dyToolCoverage(in.uv,encoded,masks,maskHeader,i); half4 result = dy_gradeMasked(sample, in.uv, source, preLUT, look1, look2, look3, look4, look5, hslMixer, whiteBalance, colorGrading, uniforms, sceneLevel,weights[0],weights[1],weights[2],weights[3],weights[4],weights[5],weights[6],weights[7],weights[8],weights[9],weights[10],weights[11]); if(options.blackWhiteMix>0.0f && options.blackWhiteMix<1.0f) { half4 color=dy_gradeMasked(sample,in.uv,source,preLUT,look1,look2,look3,look4,look5,hslMixer,whiteBalance,colorGrading,colorUniforms,sceneLevel,weights[0],weights[1],weights[2],weights[3],weights[4],weights[5],weights[6],weights[7],weights[8],weights[9],weights[10],weights[11]); result.rgb=mix(color.rgb,result.rgb,half(options.blackWhiteMix)); } if(spiderSize.x>0 && uniforms.spiderSectionEnabled>.5f && uniforms.spiderMix>0.0f){ float3 color=float3(result.rgb);float3 warped=dyVariableSpider(color,spiderSize.x,spiderSize.y,spiderSamples); result.rgb=half3(dyLimit(mix(color,warped,uniforms.spiderMix*weights[1]))); } result.a = sample.a; if (options.outputPremultiplied) result.rgb *= result.a; return result; } fragment half4 dySegmentFragment(DYRaster in [[stage_in]], texture2d source [[texture(0)]], texture3d preLUT [[texture(1)]], texture3d look1 [[texture(2)]], texture3d look2 [[texture(3)]], texture3d look3 [[texture(4)]], texture3d look4 [[texture(5)]], texture3d look5 [[texture(6)]], texture3d hslMixer [[texture(7)]], texture3d whiteBalance [[texture(8)]], texture3d colorGrading [[texture(9)]], constant DYUniforms& uniforms [[buffer(0)]], constant float& sceneLevel [[buffer(1)]], constant DYRenderOptions& options [[buffer(2)]], constant DYUniforms& colorUniforms [[buffer(3)]], device const float* spiderSamples [[buffer(4)]], constant int2& spiderSize [[buffer(5)]], device const DYToolMaskEntry* masks [[buffer(6)]], constant DYToolMaskHeader& maskHeader [[buffer(7)]], constant DYToolStageRange& stages [[buffer(8)]], texture2d skinReference [[texture(10)]], texture2d nativeSource [[texture(11)]]) { constexpr sampler sampleFilter(coord::normalized, address::clamp_to_edge, filter::linear); half4 sample = source.sample(sampleFilter, in.uv); if (!(sample.a > half(0.0))) return half4(0.0h); half4 originalSample=nativeSource.sample(sampleFilter,in.uv); float weights[12];float3 encoded=dyToolEncode(float3(originalSample.rgb)); for(int i=0;i<12;i++)weights[i]=dyToolCoverage(in.uv,encoded,masks,maskHeader,i); if(stages.suppressBlackWhite)weights[10]=0; half4 reference=skinReference.sample(sampleFilter,in.uv); float3 skinEncoded=dyToolEncode(reference.a>half(0)?float3(reference.rgb/reference.a):float3(0)); half4 result = dy_gradeSegment(sample, in.uv, nativeSource, preLUT, look1, look2, look3, look4, look5, hslMixer, whiteBalance, colorGrading, uniforms, sceneLevel,weights[0],weights[1],weights[2],weights[3],weights[4],weights[5],weights[6],weights[7],weights[8],weights[9],weights[10],weights[11],uint(stages.first),uint(stages.last),skinEncoded,encoded); if(stages.first<=9 && stages.last>=9 && options.blackWhiteMix>0.0f && options.blackWhiteMix<1.0f) { half4 color=dy_gradeSegment(sample,in.uv,nativeSource,preLUT,look1,look2,look3,look4,look5,hslMixer,whiteBalance,colorGrading,colorUniforms,sceneLevel,weights[0],weights[1],weights[2],weights[3],weights[4],weights[5],weights[6],weights[7],weights[8],weights[9],weights[10],weights[11],uint(stages.first),uint(stages.last),skinEncoded,encoded); result.rgb=mix(color.rgb,result.rgb,half(options.blackWhiteMix)); } result.a = sample.a; if (options.outputPremultiplied) result.rgb *= result.a; return result; } // Optional boundary conversion. Use this before both statistics and grading // when the host supplies premultiplied RGB; all neighborhood samples then see // the same straight RGB representation. Source and destination must differ. kernel void dyUnpremultiply(texture2d source [[texture(0)]], texture2d destination [[texture(1)]], uint2 pixel [[thread_position_in_grid]]) { if (pixel.x >= destination.get_width() || pixel.y >= destination.get_height()) return; float4 sample = source.read(pixel); if (!(sample.a > 0.0f) || !all(isfinite(sample))) { destination.write(half4(0.0h), pixel); return; } destination.write(half4(half3(sample.rgb / sample.a), half(sample.a)), pixel); } // Per-instance CPU analysis thumbnail. Host dispatches exactly 64x64 threads; // RGB is sRGB encoded, alpha is unchanged. HDR and negative values are retained // by the standard piecewise transfer rather than silently clipping the sample. kernel void dyPreview(texture2d source [[texture(0)]], device float4* outRGBA [[buffer(0)]], uint2 pixel [[thread_position_in_grid]]) { if (pixel.x >= 64 || pixel.y >= 64) return; constexpr sampler sampleFilter(coord::normalized, address::clamp_to_edge, filter::linear); half4 sample = source.sample(sampleFilter, (float2(pixel) + 0.5f) / 64.0f); float3 linear = float3(sample.rgb); float3 power = 1.055f * pow(max(linear, float3(0.0f)), float3(1.0f / 2.4f)) - 0.055f; float3 encoded = select(power, linear * 12.92f, linear <= 0.0031308f); outRGBA[pixel.y * 64 + pixel.x] = float4(encoded, float(sample.a)); } // Analysis resolution matches the reference auto-grade sample dimensions. kernel void dyAnalysis(texture2d source [[texture(0)]], device float4* outRGBA [[buffer(0)]], uint2 pixel [[thread_position_in_grid]]) { if (pixel.x >= 320 || pixel.y >= 180) return; constexpr sampler sampleFilter(coord::normalized, address::clamp_to_edge, filter::linear); half4 sample = source.sample(sampleFilter, (float2(pixel) + 0.5f) / float2(320.0f, 180.0f)); float3 linear = float3(sample.rgb); float3 power = 1.055f * pow(max(linear, float3(0.0f)), float3(1.0f / 2.4f)) - 0.055f; float3 encoded = select(power, linear * 12.92f, linear <= 0.0031308f); outRGBA[pixel.y * 320 + pixel.x] = float4(encoded, float(sample.a)); } // Native auto-grade statistics consume the input-converted RGB8 preview. // Quantization before and after the LUT mirrors the reference NSImage path. kernel void dyInputAnalysis(texture2d source [[texture(0)]], texture3d inputLUT [[texture(1)]], device float4* outRGBA [[buffer(0)]], constant float& inputStrength [[buffer(1)]], uint2 pixel [[thread_position_in_grid]]) { if (pixel.x >= 320 || pixel.y >= 180) return; constexpr sampler f(coord::normalized,address::clamp_to_edge,filter::linear); half4 sample=source.sample(f,(float2(pixel)+.5f)/float2(320,180)); float3 linear=float3(sample.rgb); float3 power=1.055f*pow(max(linear,float3(0)),float3(1.0f/2.4f))-.055f; float3 encoded=round(clamp(select(power,linear*12.92f,linear<=.0031308f),0.0f,1.0f)*255.0f)/255.0f; float strength=clamp(inputStrength,0.0f,1.0f); if(strength>0.0f){float n=float(inputLUT.get_width());float3 coord=encoded*((n-1.0f)/n)+.5f/n;encoded=mix(encoded,inputLUT.sample(f,coord).rgb,strength);} encoded=round(clamp(encoded,0.0f,1.0f)*255.0f)/255.0f; outRGBA[pixel.y*320+pixel.x]=float4(encoded,float(sample.a)); } // CST/BASIS arithmetic is reused verbatim from the versioned dayu-cst source. float4 cst_air(half4 sample, constant CSTParams& params); float4 basis_air(half4 sample, constant BasisParams& params); inline float3 dyEncode(float3 linear) { return select(1.055f*pow(max(linear,float3(0)),float3(1.0f/2.4f))-.055f,linear*12.92f,linear<=.0031308f); } inline float3 dyDecode(float3 encoded) { return select(pow(max((encoded+.055f)/1.055f,float3(0)),float3(2.4f)),encoded/12.92f,encoded<=.04045f); } kernel void dyColorManagement(texture2d source [[texture(0)]], texture2d destination [[texture(1)]], constant DayuRenderParams& p [[buffer(0)]],constant float& amount [[buffer(1)]],uint2 pos [[thread_position_in_grid]]) { if(pos.x>=source.get_width()||pos.y>=source.get_height())return; float4 sample=source.read(pos);if(!(sample.a>0)){destination.write(half4(0),pos);return;} float4 raw=float4(dyEncode(sample.rgb),sample.a),c=raw; if(p.stages&1)c=cst_air(half4(c),p.input); if(p.stages&2){if(p.reserved&8)c=cst_air(half4(c),p.basisInput);c=basis_air(half4(c),p.basis);if(p.reserved&8)c=cst_air(half4(c),p.basisOutput);} if(p.stages&4)c=cst_air(half4(c),p.output); c.rgb=mix(raw.rgb,c.rgb,amount); destination.write(half4(half3(dyDecode(c.rgb)),half(sample.a)),pos); } // Premultiplication is preserved by mixing the two equally-alpha images. kernel void dyToolBlend(texture2d before [[texture(0)]],texture2d after [[texture(1)]],texture2d output [[texture(2)]],device const DYToolMaskEntry* masks [[buffer(0)]],constant DYToolMaskHeader& h [[buffer(1)]],uint2 pos [[thread_position_in_grid]]){ if(pos.x>=output.get_width()||pos.y>=output.get_height())return;float4 a=before.read(pos),b=after.read(pos);float2 uv=(float2(pos)+.5f)/float2(output.get_width(),output.get_height());float amount=dyToolCoverage(uv,dyToolEncode(a.a>0?(h.premultiplied?a.rgb/a.a:a.rgb):float3(0)),masks,h,h.section);output.write(half4(mix(a,b,amount)),pos); } extern "C" float3 dy_skinExtra(float3 color,float3 reference,constant DYUniforms& uniforms); kernel void dyToolSkin(texture2d before [[texture(0)]],texture2d reference [[texture(1)]],texture2d output [[texture(2)]],constant DYUniforms& u [[buffer(0)]],uint2 pos [[thread_position_in_grid]]){ if(pos.x>=output.get_width()||pos.y>=output.get_height())return;constexpr sampler f(coord::normalized,address::clamp_to_edge,filter::linear);float4 a=before.read(pos),b=reference.sample(f,(float2(pos)+.5f)/float2(output.get_width(),output.get_height()));if(a.a>0){float3 c=dy_skinExtra(dyToolEncode(a.rgb/a.a),dyToolEncode(b.a>0?b.rgb/b.a:float3(0)),u);a.rgb=dyToolDecode(c)*a.a;}output.write(half4(a),pos); } fragment half4 dyToolCopyFragment(DYRaster in [[stage_in]],texture2d source [[texture(0)]]){constexpr sampler f(coord::normalized,address::clamp_to_edge,filter::linear);return source.sample(f,in.uv);}