diff --git a/research/ToolMaskPort.json b/research/ToolMaskPort.json new file mode 100644 index 0000000..d8ea570 --- /dev/null +++ b/research/ToolMaskPort.json @@ -0,0 +1,13 @@ +{ + "sourceRepository": "https://dayu.media/git/dayu/dayu-colorplate.git", + "sourceCommit": "f8950384e514685c8809fe8e8ee2dd5f16ad0bd7", + "files": { + "Core/DYMask.h": "ede701e3636c7608f5f8be3be2d95acfdd8080e751d18f89c6660bd874997101", + "Core/DYMaskOperator.h": "43fa701ad574f38ce0ab4f4d3900bb034edaaa1adc09821d2f4443ee2b687ba2", + "Core/DYTracker.hpp": "0d67d4d7d919cf3f255fe39f949c3e3ae6cad1a2ae07ad429ee45f1e23bdeb3e", + "Sources/DYMetalTracker.mm": "11b49215e9e024e5d1aa59a57dc7ab28048f569cfa3ef6943c014ad26040883d", + "Shaders/DYTracking.metal": "4949ffcc32701c95c2385e1ebd6425fbb8fe66771c801b65aaf0a308d23e155c" + }, + "status": "implementation-in-progress", + "scope": "Adapt parent mask mathematics, Metal bidirectional optical flow and deterministic affine RANSAC. No reference app runtime dependency." +} diff --git a/tools/build_kernels.py b/tools/build_kernels.py index 32f8701..2236a5c 100644 --- a/tools/build_kernels.py +++ b/tools/build_kernels.py @@ -3,6 +3,7 @@ from pathlib import Path import argparse import subprocess +from build_masked_kernel import masked_kernel def main(): @@ -17,13 +18,21 @@ def main(): objects = [] for name in ('DYGradeKernel', 'DYStatisticsKernel', 'DYLUTExportKernel', 'CSTKernel', 'BasisKernel'): target = work / (name + '.air') - subprocess.run(['xcrun', 'metal-opt', str(root / 'tools/kernels' / (name + '.ll')), + source = root / 'tools/kernels' / (name + '.ll') + if name == 'DYGradeKernel': + generated = work / 'DYGradeMasked.ll' + generated.write_text(masked_kernel(source.read_text())) + source = generated + subprocess.run(['xcrun', 'metal-opt', str(source), '-o', str(target)], check=True) objects.append(str(target)) wrapper = work / 'DYGradeWrapper.air' subprocess.run(['xcrun', '-sdk', 'macosx', 'metal', '-std=metal3.1', '-mmacosx-version-min=14.6', '-c', str(root / '大鱼调色/Plugin/DYGrade.metal'), '-o', str(wrapper)], check=True) + tracking=work / 'DYTracking.air' + subprocess.run(['xcrun','-sdk','macosx','metal','-std=metal3.1','-mmacosx-version-min=14.6','-c',str(root/'大鱼调色/Plugin/DYTracking.metal'),'-o',str(tracking)],check=True) + objects.append(str(tracking)) subprocess.run(['xcrun', '-sdk', 'macosx', 'metallib', str(wrapper), *objects, '-o', str(args.output)], check=True) print(args.output) diff --git a/tools/build_masked_kernel.py b/tools/build_masked_kernel.py new file mode 100644 index 0000000..652b39e --- /dev/null +++ b/tools/build_masked_kernel.py @@ -0,0 +1,38 @@ +"""Add per-stage coverage to a separate entry; preserve the legacy AIR function. + +Anchors are exact SSA values of the versioned source, not guessed byte offsets. +No target runtime or installed reference binary is a build dependency. +""" +import re + +def masked_kernel(source): + original = re.search(r'define <4 x half> @dy_grade\(.*?\n\}', source, re.S).group() + body = original.replace('@dy_grade(', '@dy_gradeMasked(', 1) + args = ', '.join(f'float %dyWeight{i}' for i in range(12)) + body = body.replace(') local_unnamed_addr #0 {', ', '+args+') local_unnamed_addr #0 {', 1) + # Each stage mixes against its actual input. Split basic adjustment has + # two native locations; both use the same per-module coverage. + stages = [(82,53,0),(83,82,8),(408,83,2),(409,408,6), + (410,409,9),(411,410,11),(498,411,5),(519,498,7), + (520,519,2),(521,520,10),(668,521,4),(669,668,3)] + for value, before, section in stages: + target = f'%v{value}' + lines = body.splitlines() + index = next(i for i,l in enumerate(lines) if l.startswith(' '+target+' = ')) + # Keep all PHIs first in a block, then insert the coverage operation. + end = index+1 + while end undef, float %dyWeight{section}, i64 0', + f' %dyVector{value} = shufflevector <3 x float> %dyScalar{value}, <3 x float> undef, <3 x i32> zeroinitializer', + f' {target} = tail call <3 x float> @air.mix.v3f32(<3 x float> %v{before}, <3 x float> %dyRaw{value}, <3 x float> %dyVector{value}) #1'] + body='\n'.join(lines) + skin=''' +define <3 x float> @dy_skinExtra(<3 x float> %color, <3 x float> %reference, %struct.DYUniforms addrspace(2)* %uniforms) { +entry: + %result = call fastcc <3 x float> @_ZL19applySkinProtectionDv3_fS_RU11MTLconstantK17DYUniforms(<3 x float> %color, <3 x float> %reference, %struct.DYUniforms addrspace(2)* %uniforms) + ret <3 x float> %result +} +''' + return source+'\n'+body+'\n'+skin diff --git a/大鱼调色.xcodeproj/project.pbxproj b/大鱼调色.xcodeproj/project.pbxproj index 28ff806..7befb68 100644 --- a/大鱼调色.xcodeproj/project.pbxproj +++ b/大鱼调色.xcodeproj/project.pbxproj @@ -60,12 +60,14 @@ Plugin/DYDiagnostics.mm, Plugin/DYGrade.metal, Plugin/DYInspector.mm, - Plugin/DYTheme.mm, - Plugin/DYLUTLibrary.mm, Plugin/DYLUTBrowser.mm, + Plugin/DYLUTLibrary.mm, Plugin/DYModel.mm, Plugin/DYPlugIn.mm, Plugin/DYRenderer.mm, + Plugin/DYTheme.mm, + Plugin/DYToolState.mm, + Plugin/DYTracking.metal, Plugin/Info.plist, Plugin/main.m, Plugin/Resources/DayuColorTables.bin, @@ -121,9 +123,9 @@ Plugin/Resources/InputLUTs/sony_slog3_sgamut3cine_to_rec709.dylut, "Plugin/Resources/THIRD-PARTY-NOTICES.txt", "Wrapper Application/AppDelegate.m", - "Wrapper Application/Resources/DayuColor.icns", "Wrapper Application/Info.plist", "Wrapper Application/main.m", + "Wrapper Application/Resources/DayuColor.icns", ); target = 04962E5C3095058F009952AA /* XPC Service */; }; diff --git a/大鱼调色/Plugin/DYGrade.metal b/大鱼调色/Plugin/DYGrade.metal index 5eb251b..9da0f91 100644 --- a/大鱼调色/Plugin/DYGrade.metal +++ b/大鱼调色/Plugin/DYGrade.metal @@ -1,5 +1,6 @@ #include #include "DYUniforms.h" +#include "DYToolGPU.h" #include "SpiderCore/DYColorMath.h" using namespace metal; @@ -11,6 +12,12 @@ extern "C" half4 dy_grade(half4 sample, float2 uv, texture2d source, 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); struct DYRaster { float4 position [[position]]; @@ -61,6 +68,119 @@ fragment half4 dyFragment(DYRaster in [[stage_in]], 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; +} + // 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. @@ -144,3 +264,14 @@ kernel void dyColorManagement(texture2d source [[texture(0)] 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);} diff --git a/大鱼调色/Plugin/DYInspector.mm b/大鱼调色/Plugin/DYInspector.mm index d8a55c0..b6aeb10 100644 --- a/大鱼调色/Plugin/DYInspector.mm +++ b/大鱼调色/Plugin/DYInspector.mm @@ -1,5 +1,6 @@ #import "DYInspector.h" #import "DYModel.h" +#import "DYToolState.h" #import "DYTheme.h" #import "DYLUTLibrary.h" #import "DYLUTBrowser.h" @@ -378,6 +379,7 @@ static NSImage *DYWheelImage(void) { @end #include "DYNewPanels.inc.h" +#include "DYMaskPanel.inc.h" @interface DYInspector () { id _manager; @@ -399,6 +401,7 @@ static NSImage *DYWheelImage(void) { NSMutableDictionary *_tabs; NSInteger _visibleLooks; BOOL _refreshing,_graphicUndoOpen; + BOOL _embedded;NSMutableDictionary *_stackViews;NSArray *_stackOrder;CGFloat _stackHeight; DYSpiderPanel *_spiderPanel; NSMutableDictionary *_assetLoads,*_assetLoadIDs; NSUInteger _nextAssetLoadID; @@ -410,13 +413,16 @@ static NSImage *DYWheelImage(void) { @end @implementation DYInspector +#include "DYToolInspector.inc.h" - (instancetype)initWithAPIManager:(id)manager { return [self initWithAPIManager:manager renderer:nil]; } - (instancetype)initWithAPIManager:(id)manager renderer:(DYRenderer *)renderer { if((self=[super initWithFrame:NSMakeRect(0,0,360,780)])) { _assetLoads=[NSMutableDictionary new];_assetLoadIDs=[NSMutableDictionary new];_manager=manager; _renderer=[renderer retain];_library=[DYLUTLibrary new];_tabs=[NSMutableDictionary new];_visibleLooks=1; - _sections=[DYPresentationSections() copy]; + _embedded=[manager isKindOfClass:DYToolManager.class];if(_embedded)[(id)_manager retain]; + NSArray *presentation=DYPresentationSections();if(_embedded){NSMutableArray *filtered=[NSMutableArray array];for(NSDictionary *s in presentation)if([s[@"key"]isEqual:[(DYToolManager*)manager type]])[filtered addObject:s];presentation=filtered;} + _sections=[presentation copy];_stackViews=[NSMutableDictionary new];_stackOrder=[@[]copy]; _cards=[[NSMutableArray alloc] init]; _controls=[[NSMutableDictionary alloc] init]; _assetButtons=[[NSMutableDictionary alloc] init]; _graphics=[[NSMutableArray alloc] init]; self.autoresizingMask=NSViewWidthSizable; @@ -430,13 +436,13 @@ static NSImage *DYWheelImage(void) { _save=[DYButton(@"保存预设",self,@selector(savePreset:)) retain]; _load=[DYButton(@"载入预设",self,@selector(loadPreset:)) retain]; _export=[DYButton(@"导出 LUT",self,@selector(exportLUT:)) retain]; - for(NSView *v in @[_brand,_subtitle,_resetAll,_save,_load,_export]) [self addSubview:v]; + for(NSView *v in @[_brand,_subtitle,_resetAll,_save,_load,_export]){[self addSubview:v];v.hidden=_embedded;} NSMutableArray *themes=[NSMutableArray array];for(NSInteger i=0;i<5;i++){ DYSwatchButton *b=[[[DYSwatchButton alloc]initWithFrame:NSZeroRect]autorelease];[b setButtonType:NSButtonTypePushOnPushOff];b.swatch=DYThemeSwatch(i);b.tag=i;b.target=self;b.action=@selector(selectTheme:);b.title=@"";b.bordered=NO; - b.toolTip=[DYThemeNames()[i] stringByAppendingString:@"主题"];b.accessibilityLabel=b.toolTip;[self addSubview:b];[themes addObject:b]; + b.toolTip=[DYThemeNames()[i] stringByAppendingString:@"主题"];b.accessibilityLabel=b.toolTip;[self addSubview:b];b.hidden=_embedded;[themes addObject:b]; }_themeButtons=[themes copy]; _scroll=[[DYInspectorScrollView alloc] initWithFrame:NSZeroRect]; - _scroll.hasVerticalScroller=YES; _scroll.hasHorizontalScroller=NO; _scroll.drawsBackground=NO; + _scroll.hasVerticalScroller=!_embedded; _scroll.hasHorizontalScroller=NO; _scroll.drawsBackground=NO; _scroll.autohidesScrollers=YES; _scroll.borderType=NSNoBorder; _scroll.clipsToBounds=YES;_scroll.wantsLayer=YES;_scroll.layer.masksToBounds=YES; _scroll.contentView.clipsToBounds=YES; @@ -460,6 +466,7 @@ static NSImage *DYWheelImage(void) { for(id graphic in _graphics)if([graphic isKindOfClass:DYPrimaryBalanceWheel.class])[(DYPrimaryBalanceWheel*)graphic setDelegate:nil]; for(NSProgress *p in _assetLoads.allValues)[p cancel];[_assetLoads release];[_assetLoadIDs release];[_menuScan cancel];[_menuScan release];[_pendingAssetMenuCommand release]; [[NSNotificationCenter defaultCenter] removeObserver:self]; + if(_embedded)[(id)_manager release];[_stackViews release];[_stackOrder release]; [_brand release]; [_subtitle release]; [_resetAll release]; [_save release]; [_load release]; [_export release]; [_scroll release]; [_document release]; [_sections release]; [_cards release]; [_controls release]; [_assetButtons release]; [_graphics release]; [_sampler release]; [_browser close];[_browser release];[_renderer release];[_library release];[_themeButtons release];[_tabs release]; @@ -609,6 +616,12 @@ static NSImage *DYWheelImage(void) { } NSMutableDictionary *record=[NSMutableDictionary dictionaryWithDictionary:@{@"section":section,@"view":card,@"header":header,@"enabled":enabled,@"reset":reset,@"body":body,@"collapsed":@(![@[@"primary",@"spider",@"base"]containsObject:key])}]; if([key isEqual:@"look"]){NSButton *add=DYButton(@"+",self,@selector(addLook:));add.bordered=NO;add.font=[NSFont boldSystemFontOfSize:20];add.accessibilityLabel=@"添加风格 LUT";[card addSubview:add];record[@"add"]=add;} + id host=_embedded?[(DYToolManager*)_manager host]:_manager; + NSString *nodeID=_embedded?[(DYToolManager*)_manager nodeID]:[@"base:" stringByAppendingString:key]; + DYToolMaskPanel *maskPanel=[[[DYToolMaskPanel alloc]initWithManager:host nodeID:nodeID]autorelease];[card addSubview:maskPanel];[body insertObject:maskPanel atIndex:0];record[@"maskPanel"]=maskPanel; + NSButton *mask=DYButton(@"",self,@selector(toolMask:));mask.tag=index;mask.bordered=NO;mask.image=[NSImage imageWithSystemSymbolName:@"circle.dashed.inset.filled" accessibilityDescription:@"添加蒙版"];mask.toolTip=@"添加本工具的独立蒙版";mask.accessibilityLabel=[section[@"title"]stringByAppendingString:@"添加蒙版"];[card addSubview:mask];record[@"maskButton"]=mask; + NSButton *repeat=DYButton(@"",self,@selector(repeatTool:));repeat.tag=index;repeat.bordered=NO;repeat.image=[NSImage imageWithSystemSymbolName:@"plus.square.on.square" accessibilityDescription:@"再加一层"];repeat.toolTip=@"在工具列表末尾添加一层初始化工具";repeat.accessibilityLabel=[section[@"title"]stringByAppendingString:@"再加一层"];[card addSubview:repeat];record[@"repeatButton"]=repeat; + if(_embedded){NSButton *remove=DYButton(@"删除此层",self,@selector(removeTool:));remove.identifier=@"removeTool";[card addSubview:remove];[body addObject:remove];} [_cards addObject:record]; index++; } @@ -628,6 +641,7 @@ static NSImage *DYWheelImage(void) { return row; } - (BOOL)showRow:(NSView *)row section:(NSString *)section { + if([row.identifier isEqual:@"toolMasks"])return [(DYToolMaskPanel*)row contentHeight]>0; NSString *key=row.identifier?:@"";NSInteger tab=[_tabs[section]integerValue]; if([key isEqual:@"legacyInput"])return [_tabs[@"legacyInput"]boolValue]; if([section isEqual:@"curve"] && ![key isEqual:@"curveGraph"])return NO; @@ -641,7 +655,7 @@ static NSImage *DYWheelImage(void) { if([section isEqual:@"look"]){int slot=0;if(sscanf(key.UTF8String,"asset:look%d",&slot)==1)return slot<_visibleLooks;if([key isEqual:@"postLUTStrength"])return YES;int number=0;if(sscanf(key.UTF8String,"look%dStrength",&number)==1)return number-1<_visibleLooks;return NO;} return YES; } -- (CGFloat)heightForRow:(NSView *)row {if([row.identifier isEqual:@"spiderGraph"])return 444;if([row.identifier isEqual:@"primaryBalance"])return 232;if([row.identifier hasPrefix:@"heading:"])return 27;return [row.identifier isEqual:@"curveGraph"]?240:[row.identifier isEqual:@"gradingWheels"]?292:32;} +- (CGFloat)heightForRow:(NSView *)row {if([row isKindOfClass:DYToolMaskPanel.class])return [(DYToolMaskPanel*)row contentHeight];if([row.identifier isEqual:@"spiderGraph"])return 444;if([row.identifier isEqual:@"primaryBalance"])return 232;if([row.identifier hasPrefix:@"heading:"])return 27;return [row.identifier isEqual:@"curveGraph"]?240:[row.identifier isEqual:@"gradingWheels"]?292:32;} - (void)layout { [super layout]; CGFloat w=MAX(280,self.bounds.size.width),h=self.bounds.size.height; @@ -650,23 +664,25 @@ static NSImage *DYWheelImage(void) { _resetAll.frame=NSMakeRect(w-33,16,23,24); CGFloat gap=7,bw=(w-32-gap*2)/3; _save.frame=NSMakeRect(16,50,bw,27); _load.frame=NSMakeRect(16+bw+gap,50,bw,27); _export.frame=NSMakeRect(16+(bw+gap)*2,50,bw,27); - _scroll.frame=NSMakeRect(0,88,w,MAX(80,h-88)); + _scroll.frame=_embedded?NSMakeRect(0,0,w,h):NSMakeRect(0,88,w,MAX(80,h-88)); CGFloat cw=MAX(244,_scroll.contentSize.width-32),y=8; for(NSMutableDictionary *c in _cards) { DYCard *card=c[@"view"];BOOL collapsed=[c[@"collapsed"]boolValue];NSString *key=c[@"section"][@"key"]; NSArray *body=c[@"body"];CGFloat contentHeight=0; - for(NSView *row in body)if([self showRow:row section:key])contentHeight+=[self heightForRow:row]; + for(NSView *row in body)if([self showRow:row section:key]&&(!collapsed||[row isKindOfClass:DYToolMaskPanel.class]))contentHeight+=[self heightForRow:row]; [c[@"enabled"]setFrame:NSMakeRect(12,12,20,20)]; - CGFloat titleWidth=MIN(cw-104,MAX(94,[[(NSButton *)c[@"header"]title]sizeWithAttributes:@{NSFontAttributeName:[NSFont boldSystemFontOfSize:12]}].width+36)); + CGFloat titleWidth=MIN(cw-143,MAX(94,[[(NSButton *)c[@"header"]title]sizeWithAttributes:@{NSFontAttributeName:[NSFont boldSystemFontOfSize:12]}].width+36)); [c[@"header"]setFrame:NSMakeRect(42,8,titleWidth,28)]; CGFloat headerHeight=43; - card.frame=NSMakeRect(16,y,cw,headerHeight+(collapsed?0:contentHeight+8));y+=card.frame.size.height+12; - [c[@"reset"]setFrame:NSMakeRect(cw-36,10,24,24)]; - [c[@"add"]setFrame:NSMakeRect(cw-64,10,24,24)];[c[@"add"]setEnabled:_visibleLooks<5];[c[@"add"]setHidden:collapsed]; + card.frame=NSMakeRect(16,y,cw,headerHeight+(contentHeight>0?contentHeight+8:0));y+=card.frame.size.height+12; + [c[@"reset"]setFrame:NSMakeRect(cw-34,10,24,24)]; + [c[@"repeatButton"]setFrame:NSMakeRect(cw-62,10,24,24)];[c[@"maskButton"]setFrame:NSMakeRect(cw-90,10,24,24)]; + [c[@"add"]setFrame:NSMakeRect(cw-33,headerHeight+contentHeight-28,20,24)];[c[@"add"]setEnabled:_visibleLooks<5];[c[@"add"]setHidden:collapsed]; CGFloat rowY=headerHeight; for(NSView *row in body) { - BOOL show=!collapsed&&[self showRow:row section:key];row.hidden=!show;if(!show)continue; + BOOL show=(!collapsed||[row isKindOfClass:DYToolMaskPanel.class])&&[self showRow:row section:key];row.hidden=!show;if(!show)continue; CGFloat rh=[self heightForRow:row];row.frame=NSMakeRect(12,rowY,cw-24,rh-1);rowY+=rh; + if([row.identifier isEqual:@"removeTool"]){/* NSButton fills its row. */} if([row.identifier isEqual:@"primaryBalance"])for(NSView *v in row.subviews)v.frame=row.bounds; if([row.identifier hasPrefix:@"heading:"])for(NSView *v in row.subviews)v.frame=NSMakeRect(3,7,row.bounds.size.width-6,18); if([row.identifier isEqual:@"autoControls"]||[row.identifier isEqual:@"sampleControls"]) { @@ -689,7 +705,8 @@ static NSImage *DYWheelImage(void) { [r[@"browse"]setHidden:input];[r[@"eye"]setFrame:NSMakeRect(0,5,18,20)];[r[@"browse"]setFrame:NSMakeRect(r[@"eye"]?20:0,4,20,24)];[r[@"label"]setFrame:NSMakeRect(input?2:r[@"eye"]?43:25,7,input?86:r[@"eye"]?51:69,18)]; [r[@"choose"]setFrame:NSMakeRect(97,3,MAX(65,rw-152),26)];[r[@"folder"]setFrame:NSMakeRect(rw-51,4,24,24)];[r[@"remove"]setFrame:NSMakeRect(rw-23,4,22,24)]; } - [_document setFrameSize:NSMakeSize(_scroll.contentSize.width,MAX(y,_scroll.contentSize.height))]; + for(NSString *ID in _stackOrder){DYInspector *child=_stackViews[ID];child.frame=NSMakeRect(0,y,w,MAX(60,child->_stackHeight));[child layoutSubtreeIfNeeded];CGFloat height=MAX(60,child->_stackHeight);child.frame=NSMakeRect(0,y,w,height);y+=height;} + _stackHeight=y;[_document setFrameSize:NSMakeSize(_scroll.contentSize.width,MAX(y,_scroll.contentSize.height))]; } - (id)actionAPI { return [_manager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)]; } - (void)refresh { @@ -731,6 +748,7 @@ static NSImage *DYWheelImage(void) { [c[@"enabled"]setToolTip:enabled?@"停用本组,保留参数和展开状态":@"启用本组,保留展开状态"];[c[@"enabled"]setAccessibilityHelp:[c[@"enabled"]toolTip]]; for(NSView *row in c[@"body"])row.alphaValue=enabled?1:.45; } + id maskHost=_embedded?[(DYToolManager*)_manager host]:_manager;NSDictionary *tools=DYReadTools(maskHost,t).document;for(NSDictionary *card in _cards)[card[@"maskPanel"]refreshWithDocument:tools time:t]; DYAssetState *assets=DYReadAssets(_manager,t);[_spiderPanel setMesh:assets.spiderMesh linked:assets.spiderLinked]; double profile=0,configured=0;[get getFloatValue:&profile fromParameter:2013 atTime:t];[get getFloatValue:&configured fromParameter:2236 atTime:t]; DYInspectorToken *oldToken=nil;[get getCustomParameterValue:&oldToken fromParameter:DYInspectorParameterID atTime:t]; @@ -748,9 +766,10 @@ static NSImage *DYWheelImage(void) { } @finally { [action endAction:self]; _refreshing=NO; } // Remote layout/accessibility can re-enter the host. Let the parameter // action and current callback unwind before notifying the remote view. + if(!_embedded)[self synchronizeTools]; if(groupingChanged)dispatch_async(dispatch_get_main_queue(),^{NSAccessibilityPostNotification(self,NSAccessibilityLayoutChangedNotification);}); } -- (void)postChanged { [[NSNotificationCenter defaultCenter] postNotificationName:@"DYModelChanged" object:_manager]; } +- (void)postChanged { [[NSNotificationCenter defaultCenter] postNotificationName:@"DYModelChanged" object:_embedded?[(DYToolManager*)_manager host]:_manager]; } - (void)scalarChanged:(NSControl *)sender { if(_refreshing)return; NSNumber *pid=@(sender.tag); NSDictionary *r=_controls[pid],*d=r[@"descriptor"]; if(!d)return; @@ -884,7 +903,7 @@ static NSImage *DYWheelImage(void) { @try { CMTime t=action.currentTime;id set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)]; for(NSDictionary *d in DYDescriptors())[set setFloatValue:[d[@"default"] doubleValue] toParameter:[d[@"pid"] unsignedIntValue] atTime:t]; - DYAssetState *assets=[[[DYAssetState alloc] init] autorelease];assets.paths=@{};DYWriteAssets(_manager,assets,t); + DYAssetState *assets=[[[DYAssetState alloc] init] autorelease];assets.paths=@{};DYWriteAssets(_manager,assets,t);DYWriteTools(_manager,[[[DYToolDocument alloc]init]autorelease].document,t); [set setCustomParameterValue:[[[DYInspectorToken alloc]init]autorelease] toParameter:DYInspectorParameterID atTime:t]; for(NSMutableDictionary *card in _cards)card[@"collapsed"]=@(![@[@"primary",@"spider",@"base"]containsObject:card[@"section"][@"key"]]); } @finally {[action endAction:self];} @@ -1006,15 +1025,15 @@ static NSImage *DYWheelImage(void) { } - (NSDictionary *)presetSnapshot { id action=[self actionAPI];if(!action)return nil; - NSMutableDictionary *values=[NSMutableDictionary dictionary];NSDictionary *paths=@{},*spider=nil; + NSMutableDictionary *values=[NSMutableDictionary dictionary];NSDictionary *paths=@{},*spider=nil;NSString *tools=nil; [action startAction:self]; @try { CMTime t=action.currentTime;id get=[_manager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]; for(NSDictionary *d in DYDescriptors()) {double v=[d[@"default"] doubleValue];[get getFloatValue:&v fromParameter:[d[@"pid"] unsignedIntValue] atTime:t];if(std::isfinite(v))values[d[@"key"]]=@(v);} DYUniforms effective;DYReadUniforms(_manager,t,&effective);values[@"cmConfigured"]=@(effective.cm.configured);values[@"blackWhiteMix"]=@(effective.cm.blackWhiteMix); - DYAssetState *state=DYReadAssets(_manager,t);paths=[[state.paths copy]autorelease]?:@{};spider=DYSpiderJSON(state.spiderMesh,state.spiderLinked); + DYAssetState *state=DYReadAssets(_manager,t);paths=[[state.paths copy]autorelease]?:@{};spider=DYSpiderJSON(state.spiderMesh,state.spiderLinked);NSData *toolData=[NSPropertyListSerialization dataWithPropertyList:DYReadTools(_manager,t).document format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];tools=[toolData base64EncodedStringWithOptions:0]; } @finally {[action endAction:self];} - return @{@"format":@"com.dayu.color.preset",@"version":@3,@"values":values,@"paths":paths,@"spider":spider}; + return @{@"format":@"com.dayu.color.preset",@"version":@4,@"values":values,@"paths":paths,@"spider":spider,@"tools":tools?:@""}; } - (void)savePreset:(id)sender { NSDictionary *snapshot=[self presetSnapshot];if(!snapshot)return; @@ -1027,10 +1046,11 @@ static NSImage *DYWheelImage(void) { NSOpenPanel *panel=[NSOpenPanel openPanel];panel.allowedFileTypes=@[@"json"];panel.allowsMultipleSelection=NO;panel.canChooseDirectories=NO; if([panel runModal]!=NSModalResponseOK)return; NSError *error=nil;NSData *data=[NSData dataWithContentsOfURL:panel.URL options:0 error:&error]; - if(!data||data.length>2*1024*1024){[self showError:error.localizedDescription?:@"预设文件过大"];return;} + if(!data||data.length>32*1024*1024){[self showError:error.localizedDescription?:@"预设文件过大"];return;} id json=[NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; - if(![json isKindOfClass:NSDictionary.class]||![json[@"format"] isEqual:@"com.dayu.color.preset"]||![@[@1,@2,@3]containsObject:json[@"version"]]||![json[@"values"] isKindOfClass:NSDictionary.class]||![json[@"paths"] isKindOfClass:NSDictionary.class]){[self showError:@"这不是有效的大鱼调色预设。"];return;} - NSDictionary *values=json[@"values"],*paths=json[@"paths"];NSData *mesh=[json[@"version"]isEqual:@3]?DYSpiderFromJSON(json[@"spider"]):nil;if([json[@"version"]isEqual:@3]&&!mesh){[self showError:@"预设包含无效蜘蛛盘,当前调色未修改。"];return;} + if(![json isKindOfClass:NSDictionary.class]||![json[@"format"] isEqual:@"com.dayu.color.preset"]||![@[@1,@2,@3,@4]containsObject:json[@"version"]]||![json[@"values"] isKindOfClass:NSDictionary.class]||![json[@"paths"] isKindOfClass:NSDictionary.class]){[self showError:@"这不是有效的大鱼调色预设。"];return;} + NSDictionary *values=json[@"values"],*paths=json[@"paths"];NSData *mesh=[json[@"version"]integerValue]>=3?DYSpiderFromJSON(json[@"spider"]):nil;if([json[@"version"]integerValue]>=3&&!mesh){[self showError:@"预设包含无效蜘蛛盘,当前调色未修改。"];return;} + NSDictionary *tools=[[[DYToolDocument alloc]init]autorelease].document;if([json[@"version"]integerValue]>=4){id encoded=json[@"tools"];NSData *binary=[encoded isKindOfClass:NSString.class]?[[[NSData alloc]initWithBase64EncodedString:encoded options:0]autorelease]:nil;tools=binary?[NSPropertyListSerialization propertyListWithData:binary options:NSPropertyListImmutable format:NULL error:nil]:nil;if(!DYValidToolDocument(tools)){[self showError:@"预设包含无效工具或蒙版,当前调色未修改。"];return;}} for(NSDictionary *d in DYDescriptors()) { id v=values[d[@"key"]];if(!v)continue; if(![v isKindOfClass:NSNumber.class]||!std::isfinite([v doubleValue])||[v doubleValue]<[d[@"min"] doubleValue]||[v doubleValue]>[d[@"max"] doubleValue]||(d[@"values"]&&![d[@"values"]containsObject:v])){[self showError:@"预设包含无效参数,尚未修改当前调色。"];return;} @@ -1048,7 +1068,7 @@ static NSImage *DYWheelImage(void) { CMTime t=action.currentTime;id set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)]; for(NSDictionary *d in DYDescriptors())if(values[d[@"key"]])[set setFloatValue:[values[d[@"key"]] doubleValue] toParameter:[d[@"pid"] unsignedIntValue] atTime:t]; if([json[@"version"]isEqual:@1]&&!values[@"cmConfigured"]){[set setFloatValue:-1 toParameter:2236 atTime:t];[set setFloatValue:1 toParameter:2270 atTime:t];} - DYAssetState *assets=[[[DYAssetState alloc] init] autorelease];assets.paths=validPaths;assets.spiderMesh=mesh;assets.spiderLinked=mesh?[json[@"spider"][@"linked"]boolValue]:YES;DYWriteAssets(_manager,assets,t); + DYAssetState *assets=[[[DYAssetState alloc] init] autorelease];assets.paths=validPaths;assets.spiderMesh=mesh;assets.spiderLinked=mesh?[json[@"spider"][@"linked"]boolValue]:YES;DYWriteAssets(_manager,assets,t);DYWriteTools(_manager,tools,t); } @finally {[action endAction:self];} [self postChanged]; if(missing.count)[self showError:[@"调色参数已恢复,以下 LUT 文件需要重新选择:\n" stringByAppendingString:[missing componentsJoinedByString:@"\n"]]]; diff --git a/大鱼调色/Plugin/DYMaskPanel.inc.h b/大鱼调色/Plugin/DYMaskPanel.inc.h new file mode 100644 index 0000000..0afb38a --- /dev/null +++ b/大鱼调色/Plugin/DYMaskPanel.inc.h @@ -0,0 +1,61 @@ +// Native per-tool mask editor, shared by original and repeated tool cards. +@interface DYToolMaskPanel : DYFlippedView +@property(nonatomic,readonly) CGFloat contentHeight; +- (instancetype)initWithManager:(id)manager nodeID:(NSString*)nodeID; +- (void)refreshWithDocument:(NSDictionary*)document time:(CMTime)time; +- (void)addMenu:(NSView*)anchor; +@end +@implementation DYToolMaskPanel { + id _host;NSString *_nodeID,*_maskID;NSDictionary *_document;CMTime _time; + NSPopUpButton *_list,*_combine;NSButton *_eye,*_add,*_remove,*_invert,*_canvas,*_clear;NSMutableArray *_rows,*_tracking;NSTextField *_status;BOOL _refreshing;CGFloat _contentHeight; +} +@synthesize contentHeight=_contentHeight; +- (instancetype)initWithManager:(id)manager nodeID:(NSString*)nodeID{ + if((self=[super initWithFrame:NSZeroRect])){_host=manager;_nodeID=[nodeID copy];_rows=[NSMutableArray new];_tracking=[NSMutableArray new];self.identifier=@"toolMasks"; + _list=[[NSPopUpButton alloc]initWithFrame:NSZeroRect pullsDown:NO];_list.target=self;_list.action=@selector(selection:);_list.font=[NSFont systemFontOfSize:10];_list.accessibilityLabel=@"本层蒙版";[self addSubview:_list]; + _eye=[DYButton(@"",self,@selector(enabled:))retain];_eye.image=[NSImage imageWithSystemSymbolName:@"eye" accessibilityDescription:@"蒙版启用"];_eye.bordered=NO;[_eye setButtonType:NSButtonTypePushOnPushOff];[self addSubview:_eye]; + _add=[DYButton(@"+",self,@selector(add:))retain];_add.toolTip=@"再添加一个蒙版";_add.accessibilityLabel=_add.toolTip;[self addSubview:_add]; + _remove=[DYButton(@"−",self,@selector(remove:))retain];_remove.toolTip=@"删除选中的蒙版";_remove.accessibilityLabel=_remove.toolTip;[self addSubview:_remove]; + _combine=[[NSPopUpButton alloc]initWithFrame:NSZeroRect pullsDown:NO];[_combine addItemsWithTitles:@[@"相加",@"减去",@"相交"]];_combine.target=self;_combine.action=@selector(combine:);_combine.accessibilityLabel=@"蒙版组合方式";[self addSubview:_combine]; + _invert=[[NSButton checkboxWithTitle:@"反转" target:self action:@selector(inverted:)]retain];[self addSubview:_invert]; + _canvas=[DYButton(@"画面编辑",self,@selector(canvas:))retain];_canvas.toolTip=@"在宿主画面拖动中心、大小、旋转与钢笔节点;回车闭合钢笔";_canvas.accessibilityLabel=@"编辑本层蒙版画面控件";[self addSubview:_canvas]; + _clear=[DYButton(@"清除轨迹",self,@selector(clear:))retain];[self addSubview:_clear]; + NSArray *names=@[@"强度",@"羽化",@"中心 X",@"中心 Y",@"宽度",@"高度",@"旋转",@"渐变宽度",@"色相中心",@"色相范围",@"色相柔边",@"饱和度下限",@"饱和度上限",@"亮度下限",@"亮度上限",@"输入黑",@"输入白",@"输入伽马"]; + for(NSInteger i=0;i=2&&i<=6&&p.kind<4)||(i==7&&p.kind==3)||(i>=8&&i<=14&&p.kind==4)||(i>=15&&p.kind>=4);NSDictionary *row=_rows[i];for(NSView *v in row.allValues)v.hidden=!show;if(!show)continue;visible++;double lo=0,hi=1;if(i==2||i==3)lo=-1,hi=2;if(i==4||i==5||i==7)lo=.001,hi=2;if(i==6)lo=-180,hi=180;if(i==8)hi=360;if(i==9||i==10)hi=180;if(i==15)hi=.99;if(i==16)lo=.01,hi=2;if(i==17)lo=.01,hi=4;NSSlider *slider=row[@"slider"];slider.minValue=lo;slider.maxValue=hi;slider.doubleValue=values[i];[row[@"field"]setStringValue:[NSString stringWithFormat:@"%.3f",values[i]]];} + BOOL shape=p.kind<3;for(NSButton *b in _tracking)b.hidden=!shape;_clear.hidden=!shape;_clear.enabled=[m[@"keys"]count]>0; + _status.stringValue=m[@"status"]?:([m[@"keys"]count]?[NSString stringWithFormat:@"%lu 个轨迹键 · 修改几何会在当前帧建立手工键",(unsigned long)[m[@"keys"]count]]:p.kind==2?@"画面编辑:拖动节点;⌘ 点击加点,回车闭合。":@"各蒙版只影响当前工具层"); + _contentHeight=108+visible*27+(shape?63:0)+36;[self setNeedsLayout:YES];_refreshing=NO; +} +- (void)layout{[super layout];CGFloat w=self.bounds.size.width;_eye.frame=NSMakeRect(0,2,20,24);_list.frame=NSMakeRect(22,1,MAX(60,w-82),26);_add.frame=NSMakeRect(w-57,1,26,25);_remove.frame=NSMakeRect(w-29,1,26,25);_combine.frame=NSMakeRect(0,33,83,25);_invert.frame=NSMakeRect(88,34,58,23);_canvas.frame=NSMakeRect(w-94,33,94,25);CGFloat y=67;for(NSDictionary *r in _rows){NSTextField *label=r[@"label"];if(label.hidden)continue;label.frame=NSMakeRect(2,y+4,68,18);[r[@"slider"]setFrame:NSMakeRect(72,y+4,MAX(20,w-133),18)];[r[@"field"]setFrame:NSMakeRect(w-57,y+1,55,23)];y+=27;}if(![_tracking[0]isHidden]){CGFloat bw=(w-8)/3;for(int i=0;i<6;i++)[_tracking[i]setFrame:NSMakeRect((i%3)*(bw+4),y+(i/3)*28,bw,25)];y+=58;_clear.frame=NSMakeRect(0,y,w,25);y+=29;}_status.frame=NSMakeRect(2,y+2,w-4,33);} +- (void)edit:(NSString*)title block:(void (^)(NSMutableDictionary*,NSMutableDictionary*))block{ + ida=[_host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(_host,a.currentTime).document);NSMutableArray *masks=(id)DYMasksForTool(doc,_nodeID);NSMutableDictionary *mask=nil;for(NSMutableDictionary *m in masks)if([m[@"id"]isEqual:_maskID])mask=m;if(!mask)return;block(doc,mask);if(!DYValidToolDocument(doc)){NSBeep();return;}idundo=[_host apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:title];DYWriteTools(_host,doc,a.currentTime);[undo endUndoGroup];}@finally{[a endAction:self];}[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:_host];} +- (void)add:(id)sender{[self addMenu:_add];} +- (void)addMenu:(NSView*)anchor{NSMenu *menu=[[[NSMenu alloc]initWithTitle:@"添加蒙版"]autorelease];for(int i=0;i<6;i++){NSMenuItem *item=[menu addItemWithTitle:@[@"椭圆",@"矩形",@"钢笔",@"线性渐变",@"HSL 选区",@"亮度选区"][i] action:@selector(addKind:) keyEquivalent:@""];item.target=self;item.tag=i;}[menu popUpMenuPositioningItem:nil atLocation:NSMakePoint(0,anchor.bounds.size.height) inView:anchor];} +- (void)addKind:(NSMenuItem*)sender{ + ida=[_host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(_host,a.currentTime).document);NSMutableArray *masks=[[DYMasksForTool(doc,_nodeID)mutableCopy]autorelease];if(masks.count>=DYToolMaskLimit){NSBeep();return;}NSDictionary *mask=DYNewMask(sender.tag);[masks addObject:mask];if(!DYSetToolMasks(doc,_nodeID,masks))return;idundo=[_host apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:@"添加工具蒙版"];DYWriteTools(_host,doc,a.currentTime);[undo endUndoGroup];[_maskID release];_maskID=[mask[@"id"]copy];}@finally{[a endAction:self];}[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:_host];[self canvas:nil];} +- (void)selection:(id)sender{NSArray *m=DYMasksForTool(_document,_nodeID);if(_list.indexOfSelectedItem<0||_list.indexOfSelectedItem>=m.count)return;[_maskID release];_maskID=[m[_list.indexOfSelectedItem][@"id"]copy];[self refreshWithDocument:_document time:_time];[self canvas:nil];[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:_host];} +- (void)remove:(id)sender{[self edit:@"删除工具蒙版" block:^(NSMutableDictionary *doc,NSMutableDictionary *mask){NSMutableArray *masks=[[DYMasksForTool(doc,self->_nodeID)mutableCopy]autorelease];[masks removeObject:mask];DYSetToolMasks(doc,self->_nodeID,masks);}];} +- (void)enabled:(NSButton*)sender{[self edit:@"启停蒙版" block:^(NSMutableDictionary *d,NSMutableDictionary *m){m[@"enabled"]=@(sender.state==NSControlStateValueOn);}];} +- (void)combine:(id)sender{[self edit:@"蒙版组合" block:^(NSMutableDictionary *d,NSMutableDictionary *m){m[@"combine"]=@(self->_combine.indexOfSelectedItem);}];} +- (void)inverted:(NSButton*)sender{[self edit:@"反转蒙版" block:^(NSMutableDictionary *d,NSMutableDictionary *m){DYMaskParameters p;[m[@"parameters"]getBytes:&p length:sizeof(p)];if(sender.state)p.flags|=DYMaskInvert;else p.flags&=~DYMaskInvert;m[@"parameters"]=[NSData dataWithBytes:&p length:sizeof(p)];}];} +- (void)valueChanged:(NSControl*)sender{if(_refreshing)return;double value=sender.doubleValue;if(!std::isfinite(value)){NSBeep();return;}NSInteger i=sender.tag;[self edit:@"调整工具蒙版" block:^(NSMutableDictionary *d,NSMutableDictionary *m){DYMaskParameters p=DYMaskAtTime(m,self->_time);float *fields[]={&p.strength,&p.feather,&p.centerX,&p.centerY,&p.width,&p.height,&p.angle,&p.gradientWidth,&p.hueCenterTurns,&p.hueCoreHalfWidth,&p.hueSoftWidth,&p.saturationRange.low,&p.saturationRange.high,&p.lightnessRange.low,&p.lightnessRange.high,&p.inputBlack,&p.inputWhite,&p.inputGamma};*fields[i]=(i==6?value*M_PI/180:i>=8&&i<=10?value/360:value);if(p.kind==DYMaskHSLKey)p.flags|=DYMaskHueEnabled|DYMaskSaturationEnabled|DYMaskLightnessEnabled;if(!dyValidMaskParameters(p))return;if([m[@"keys"]count]&&i<8){NSMutableArray *keys=[[m[@"keys"]mutableCopy]autorelease];[keys filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDictionary *key,NSDictionary *bindings){CMTime t=CMTimeMakeWithEpoch([key[@"value"]longLongValue],[key[@"scale"]intValue],[key[@"epoch"]longLongValue]);return CMTimeCompare(t,self->_time)!=0;}]];[keys addObject:DYMaskKey(self->_time,p,YES,1)];[keys sortUsingComparator:^NSComparisonResult(NSDictionary *a,NSDictionary *b){CMTime x=CMTimeMakeWithEpoch([a[@"value"]longLongValue],[a[@"scale"]intValue],[a[@"epoch"]longLongValue]),y=CMTimeMakeWithEpoch([b[@"value"]longLongValue],[b[@"scale"]intValue],[b[@"epoch"]longLongValue]);return (NSComparisonResult)CMTimeCompare(x,y);}];m[@"keys"]=keys;}else m[@"parameters"]=[NSData dataWithBytes:&p length:sizeof(p)];}];} +- (void)canvas:(id)sender{[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolCanvasSelection" object:_host userInfo:@{@"node":_nodeID,@"mask":_maskID?:@""}];} +- (void)clear:(id)sender{[self edit:@"清除蒙版轨迹" block:^(NSMutableDictionary *d,NSMutableDictionary *m){DYMaskParameters p=DYMaskAtTime(m,self->_time);m[@"parameters"]=[NSData dataWithBytes:&p length:sizeof(p)];m[@"keys"]=@[];[m removeObjectForKey:@"status"];}];} +- (void)track:(NSButton*)sender{[self canvas:nil];[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolTrack" object:_host userInfo:@{@"node":_nodeID,@"mask":_maskID?:@"",@"direction":@(sender.tag)}];} +- (void)trackingStatus:(NSNotification*)n{if([n.userInfo[@"node"]isEqual:_nodeID])_status.stringValue=n.userInfo[@"message"]?:@"";} +@end diff --git a/大鱼调色/Plugin/DYModel.mm b/大鱼调色/Plugin/DYModel.mm index 15d6d12..1e365b8 100644 --- a/大鱼调色/Plugin/DYModel.mm +++ b/大鱼调色/Plugin/DYModel.mm @@ -1,4 +1,5 @@ #import "DYModel.h" +#import "DYToolState.h" #include #include "DYSpiderState.h" NSString *const DYModelChanged=@"DYModelChanged"; @@ -164,6 +165,8 @@ BOOL DYCreateParameters(idm,NSError**error){id -@interface DYPlugIn : NSObject +@interface DYPlugIn : NSObject @property(assign) id apiManager; @end diff --git a/大鱼调色/Plugin/DYPlugIn.mm b/大鱼调色/Plugin/DYPlugIn.mm index 6aad3b4..015591c 100644 --- a/大鱼调色/Plugin/DYPlugIn.mm +++ b/大鱼调色/Plugin/DYPlugIn.mm @@ -4,30 +4,38 @@ #import "DYInspector.h" #import "DYColorTables.h" #import "DYAutoGrade.h" +#import "DYToolState.h" +#import +#include "MaskCore/DYTracker.hpp" +#include +#include "DYToolHostDeclarations.inc.h" @implementation DYPlugIn { DYRenderer *_renderer; BOOL _copyAnalyzed; +#include "DYToolHostIvars.inc.h" } -- (instancetype)initWithAPIManager:(id)manager{if((self=[super init])){_apiManager=manager;_renderer=[DYRenderer new];NSNotificationCenter*n=NSNotificationCenter.defaultCenter;[n addObserver:self selector:@selector(exportRequested:) name:@"DYExportLUT" object:manager];[n addObserver:self selector:@selector(autoRequested:) name:@"DYAutoGrade" object:manager];[n addObserver:self selector:@selector(autoRequested:) name:@"DYAutoWhiteBalance" object:manager];[n addObserver:self selector:@selector(whiteBalanceRequested:) name:@"DYWhiteBalanceColor" object:manager];}return self;} -- (void)dealloc{[NSNotificationCenter.defaultCenter removeObserver:self];[_renderer release];[super dealloc];} +#include "DYToolHostMethods.inc.h" +- (instancetype)initWithAPIManager:(id)manager{if((self=[super init])){_apiManager=manager;_renderer=[DYRenderer new];[self initializeToolHost];NSNotificationCenter*n=NSNotificationCenter.defaultCenter;[n addObserver:self selector:@selector(exportRequested:) name:@"DYExportLUT" object:manager];[n addObserver:self selector:@selector(autoRequested:) name:@"DYAutoGrade" object:manager];[n addObserver:self selector:@selector(autoRequested:) name:@"DYAutoWhiteBalance" object:manager];[n addObserver:self selector:@selector(whiteBalanceRequested:) name:@"DYWhiteBalanceColor" object:manager];}return self;} +- (void)dealloc{[self tearDownToolHost];[NSNotificationCenter.defaultCenter removeObserver:self];[_renderer release];[super dealloc];} - (BOOL)properties:(NSDictionary**)p error:(NSError**)e{*p=@{kFxPropertyKey_MayRemapTime:@NO,kFxPropertyKey_PixelTransformSupport:@(kFxPixelTransform_ScaleTranslate),kFxPropertyKey_VariesWhenParamsAreStatic:@NO,kFxPropertyKey_DesiredProcessingColorInfo:@(kFxImageColorInfo_RGB_LINEAR),kFxPropertyKey_NeedsFullBuffer:@YES};return YES;} - (BOOL)addParametersWithError:(NSError**)e{return DYCreateParameters(_apiManager,e);} -- (NSSet*)classesForCustomParameterID:(UInt32)pid{return pid==DYAssetsParameterID?[NSSet setWithObjects:DYAssetState.class,NSDictionary.class,NSString.class,NSData.class,nil]:[NSSet setWithObjects:DYInspectorToken.class,NSDictionary.class,NSString.class,NSNumber.class,nil];} -- (NSView*)createViewForParameterID:(UInt32)pid{return pid==DYInspectorParameterID?[[DYInspector alloc]initWithAPIManager:_apiManager renderer:_renderer]:[[NSView alloc]initWithFrame:NSZeroRect];} -- (BOOL)parameterChanged:(UInt32)pid atTime:(CMTime)t error:(NSError**)e{if(pid==2013||pid==2014||(pid>=2236&&pid<2400)||pid==DYAssetsParameterID)[_renderer invalidatePreview];dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:self.apiManager];});return YES;} +- (NSSet*)classesForCustomParameterID:(UInt32)pid{return pid==DYToolsParameterID?[NSSet setWithObjects:DYToolDocument.class,NSDictionary.class,NSArray.class,NSString.class,NSNumber.class,NSData.class,nil]:pid==DYAssetsParameterID?[NSSet setWithObjects:DYAssetState.class,NSDictionary.class,NSString.class,NSData.class,nil]:[NSSet setWithObjects:DYInspectorToken.class,NSDictionary.class,NSString.class,NSNumber.class,nil];} +- (NSView*)createViewForParameterID:(UInt32)pid{[self scheduleToolCanvasRegistration];return pid==DYInspectorParameterID?[[DYInspector alloc]initWithAPIManager:_apiManager renderer:_renderer]:[[NSView alloc]initWithFrame:NSZeroRect];} +- (BOOL)parameterChanged:(UInt32)pid atTime:(CMTime)t error:(NSError**)e{if(pid==DYToolsParameterID||pid==2013||pid==2014||(pid>=2236&&pid<2400)||pid==DYAssetsParameterID)[_renderer invalidatePreview];dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:self.apiManager];});return YES;} - (BOOL)pluginState:(NSData**)state atTime:(CMTime)t quality:(FxQuality)q error:(NSError**)e{ - DYUniforms u;DYReadUniforms(_apiManager,t,&u);DYAssetState*a=DYReadAssets(_apiManager,t);double copyAuto=0;[[_apiManager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getFloatValue:©Auto fromParameter:8800 atTime:t];NSDictionary*s=@{@"schema":@1,@"copyAuto":@(copyAuto>.5),@"uniforms":[NSData dataWithBytes:&u length:sizeof(u)],@"paths":a.paths?:@{},@"spider":a.spiderMesh?:[NSData data]};*state=[NSPropertyListSerialization dataWithPropertyList:s format:NSPropertyListBinaryFormat_v1_0 options:0 error:e];return *state!=nil; + DYUniforms u;DYReadUniforms(_apiManager,t,&u);DYAssetState*a=DYReadAssets(_apiManager,t);double copyAuto=0;[[_apiManager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getFloatValue:©Auto fromParameter:8800 atTime:t];NSDictionary*s=@{@"schema":@2,@"tools":DYToolRenderSnapshot(DYReadTools(_apiManager,t).document,t),@"copyAuto":@(copyAuto>.5),@"uniforms":[NSData dataWithBytes:&u length:sizeof(u)],@"paths":a.paths?:@{},@"spider":a.spiderMesh?:[NSData data]};*state=[NSPropertyListSerialization dataWithPropertyList:s format:NSPropertyListBinaryFormat_v1_0 options:0 error:e];return *state!=nil; } - (BOOL)destinationImageRect:(FxRect*)rect sourceImages:(NSArray*)src destinationImage:(FxImageTile*)dst pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{if(!src.count)return NO;*rect=src[0].imagePixelBounds;return YES;} - (BOOL)sourceTileRect:(FxRect*)rect sourceImageIndex:(NSUInteger)i sourceImages:(NSArray*)src destinationTileRect:(FxRect)dstRect destinationImage:(FxImageTile*)dst pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{if(i>=src.count)return NO;*rect=src[i].imagePixelBounds;return YES;} - (BOOL)renderDestinationImage:(FxImageTile*)dst sourceImages:(NSArray*)src pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{ - if(!src.count||!src[0].ioSurface||!dst.ioSurface||!s.length)return NO;NSDictionary*p=[NSPropertyListSerialization propertyListWithData:s options:NSPropertyListImmutable format:NULL error:e];if(![p isKindOfClass:NSDictionary.class])return NO;NSData*b=p[@"uniforms"];if(![p[@"schema"]isEqual:@1]||![b isKindOfClass:NSData.class]||b.length!=sizeof(DYUniforms)||![p[@"paths"]isKindOfClass:NSDictionary.class])return NO;DYUniforms u;[b getBytes:&u length:sizeof(u)];BOOL ok=[_renderer renderSource:src[0] destination:dst uniforms:u paths:p[@"paths"] spider:p[@"spider"] error:e];if(ok){BOOL analyze=NO;@synchronized(self){if(![p[@"copyAuto"]boolValue])_copyAnalyzed=NO;else if(!_copyAnalyzed){_copyAnalyzed=YES;analyze=YES;}}if(analyze){NSDictionary*values=DYAutoGrade([_renderer preview]);if(values)dispatch_async(dispatch_get_main_queue(),^{[self applyValues:values];});}}return ok; + if(!src.count||!src[0].ioSurface||!dst.ioSurface||!s.length)return NO;NSDictionary*p=[NSPropertyListSerialization propertyListWithData:s options:NSPropertyListImmutable format:NULL error:e];if(![p isKindOfClass:NSDictionary.class])return NO;NSData*b=p[@"uniforms"];if(![@[@1,@2]containsObject:p[@"schema"]]||![b isKindOfClass:NSData.class]||b.length!=sizeof(DYUniforms)||![p[@"paths"]isKindOfClass:NSDictionary.class])return NO;DYUniforms u;[b getBytes:&u length:sizeof(u)];BOOL ok=[_renderer renderSource:src[0] destination:dst uniforms:u paths:p[@"paths"] spider:p[@"spider"] tools:p[@"tools"] error:e];if(ok){BOOL analyze=NO;@synchronized(self){if(![p[@"copyAuto"]boolValue])_copyAnalyzed=NO;else if(!_copyAnalyzed){_copyAnalyzed=YES;analyze=YES;}}if(analyze){NSDictionary*values=DYAutoGrade([_renderer preview]);if(values)dispatch_async(dispatch_get_main_queue(),^{[self applyValues:values];});}}return ok; } - (void)alert:(NSString*)message{dispatch_async(dispatch_get_main_queue(),^{NSAlert*a=[NSAlert new];a.messageText=@"大鱼调色";a.informativeText=message?:@"操作未完成";[a runModal];[a release];});} - (void)exportRequested:(NSNotification*)n{ - NSURL*url=n.userInfo[@"url"];if(![url isKindOfClass:NSURL.class])return;ida=[_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];[a startAction:self];DYUniforms u;DYReadUniforms(_apiManager,a.currentTime,&u);DYAssetState *assets=DYReadAssets(_apiManager,a.currentTime);NSDictionary*paths=[assets.paths copy];NSData *mesh=[assets.spiderMesh copy];[a endAction:self];NSError*e=nil;BOOL ok=[_renderer exportLUT:url uniforms:u paths:paths spider:mesh error:&e];[mesh release];[paths release];if(!ok)[self alert:e.localizedDescription]; + NSURL*url=n.userInfo[@"url"];if(![url isKindOfClass:NSURL.class])return;ida=[_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];[a startAction:self];DYUniforms u;DYReadUniforms(_apiManager,a.currentTime,&u);DYAssetState *assets=DYReadAssets(_apiManager,a.currentTime);NSDictionary*paths=[assets.paths copy];NSData *mesh=[assets.spiderMesh copy];NSDictionary *tools=[DYReadTools(_apiManager,a.currentTime).document copy];[a endAction:self];NSError*e=nil;BOOL ok=[_renderer exportLUT:url uniforms:u paths:paths spider:mesh tools:tools error:&e];[tools release];[mesh release];[paths release];if(!ok)[self alert:e.localizedDescription]; } - (void)applyValues:(NSDictionary*)values{if(!values){[self alert:@"尚未拿到当前片段画面,请移动播放头后重试。"];return;}ida=[_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];[a startAction:self];@try{ids=[_apiManager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];for(NSDictionary*r in DYDescriptors()){NSNumber*v=values[r[@"key"]];if(v)[s setFloatValue:v.doubleValue toParameter:[r[@"pid"]unsignedIntValue] atTime:a.currentTime];}}@finally{[a endAction:self];}[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:_apiManager];} - (void)autoRequested:(NSNotification*)n{NSData*frame=[_renderer preview];[self applyValues:[n.name isEqual:@"DYAutoGrade"]?DYAutoGrade(frame):DYAutoWhiteBalance(frame)];} - (void)whiteBalanceRequested:(NSNotification*)n{NSColor*c=[n.userInfo[@"color"]colorUsingColorSpace:NSColorSpace.sRGBColorSpace];if(!c)return;float temp=0,tint=0;if([DYColorTables neutralizeColor:(vector_float3){(float)c.redComponent,(float)c.greenComponent,(float)c.blueComponent} temperature:&temp tint:&tint])[self applyValues:@{@"temperature":@(temp),@"tint":@(tint)}];else [self alert:@"所选颜色过暗,请选择白色或中性灰区域。"];} @end +#include "DYToolOSC.inc.h" diff --git a/大鱼调色/Plugin/DYRenderer.h b/大鱼调色/Plugin/DYRenderer.h index 60e5695..2b03423 100644 --- a/大鱼调色/Plugin/DYRenderer.h +++ b/大鱼调色/Plugin/DYRenderer.h @@ -2,6 +2,7 @@ #import #import #import "DYUniforms.h" +#import "DYToolState.h" @interface DYRenderer : NSObject /// Decode and upload before committing a host parameter. The renderer retains /// the immutable selected contents independently of the thumbnail cache. @@ -10,6 +11,8 @@ - (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths error:(NSError**)error; - (BOOL)renderSource:(FxImageTile*)source destination:(FxImageTile*)destination uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths spider:(NSData*)spider error:(NSError**)error; - (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths spider:(NSData*)spider error:(NSError**)error; +- (BOOL)renderSource:(FxImageTile*)source destination:(FxImageTile*)destination uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools error:(NSError**)error; +- (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools error:(NSError**)error; - (NSData*)preview; /// Display-encoded float RGBA, 320×180, with the visually top row first. /// Analysis preview retains the host texture's original row order separately. diff --git a/大鱼调色/Plugin/DYRenderer.mm b/大鱼调色/Plugin/DYRenderer.mm index 4154036..18612c3 100644 --- a/大鱼调色/Plugin/DYRenderer.mm +++ b/大鱼调色/Plugin/DYRenderer.mm @@ -1,6 +1,7 @@ #import "DYRenderer.h" #import "DYModel.h" #include "DYSpiderState.h" +#include "DYToolGPU.h" #import "DYColorTables.h" #import "DYLUTLibrary.h" #import @@ -11,17 +12,19 @@ static BOOL fail(NSError**e,NSString*m){if(e)*e=[NSError errorWithDomain:@"com.d static NSArray *inputFiles(){return @[@"",@"apple_log_to_rec709",@"arri_logc3_to_rec709",@"arri_logc4_to_rec709",@"blackmagic_film_gen5_to_rec709",@"canon_clog_bt709_to_rec709",@"canon_clog2_cinema_gamut_to_rec709",@"canon_clog3_cinema_gamut_to_rec709",@"dji_dlog_to_rec709",@"dji_dlog_m_to_rec709",@"fujifilm_flog_to_rec709",@"fujifilm_flog2_to_rec709",@"nikon_nlog_to_rec709",@"panasonic_vlog_vgamut_to_rec709",@"red_log3g10_rwg_to_rec709",@"sony_slog2_sgamut_to_rec709",@"sony_slog3_sgamut3cine_to_rec709",@"sony_hlg_bt2020_to_rec709"];} static id texture3D(idd,const float*values,NSUInteger n){MTLTextureDescriptor*t=[MTLTextureDescriptor new];t.textureType=MTLTextureType3D;t.pixelFormat=MTLPixelFormatRGBA32Float;t.width=n;t.height=n;t.depth=n;t.storageMode=MTLStorageModeShared;t.usage=MTLTextureUsageShaderRead;idx=[d newTextureWithDescriptor:t];[t release];if(x)[x replaceRegion:MTLRegionMake3D(0,0,0,n,n,n) mipmapLevel:0 slice:0 withBytes:values bytesPerRow:n*16 bytesPerImage:n*n*16];return [x autorelease];} // A synthetic texture lattice uses exactly the production render path for Cube export. -@interface DYExportTile : FxImageTile { id _tex; uint64_t _registry; } +@interface DYExportTile : FxImageTile { id _tex; uint64_t _registry; FxRect _bounds;FxImageOrigin _origin; } - (instancetype)initWithTexture:(id)texture registry:(uint64_t)registry; +- (void)setBounds:(FxRect)bounds origin:(FxImageOrigin)origin; @end @implementation DYExportTile -- (instancetype)initWithTexture:(id)texture registry:(uint64_t)registry{if((self=[super init])){_tex=[texture retain];_registry=registry;}return self;} +- (instancetype)initWithTexture:(id)texture registry:(uint64_t)registry{if((self=[super init])){_tex=[texture retain];_registry=registry;_bounds=(FxRect){0,0,(SInt32)texture.width,(SInt32)texture.height};_origin=kFxImageOrigin_TOP_LEFT;}return self;} - (void)dealloc{[_tex release];[super dealloc];} - (id)metalTextureForDevice:(id)d{return d.registryID==_registry?_tex:nil;} -- (FxRect)tilePixelBounds{return (FxRect){0,0,(SInt32)_tex.width,(SInt32)_tex.height};} +- (void)setBounds:(FxRect)bounds origin:(FxImageOrigin)origin{_bounds=bounds;_origin=origin;} +- (FxRect)tilePixelBounds{return _bounds;} - (FxRect)imagePixelBounds{return self.tilePixelBounds;} - (uint64_t)deviceRegistryID{return _registry;} -- (FxImageOrigin)imageOrigin{return kFxImageOrigin_TOP_LEFT;} +- (FxImageOrigin)imageOrigin{return _origin;} @end static BOOL managed(DYUniforms u,NSDictionary *paths){return u.cm.configured>=0&&(u.cm.configured>.5||(![paths[@"input"]length]&&u.inputProfile<.5));} static BOOL identityCM(DYUniforms u){ @@ -55,9 +58,11 @@ static void bypassIdleSkin(DYUniforms *u){ NSData *_preview,*_lookLUTPreview; CFTimeInterval _lastPreview; BOOL _exporting; + NSDictionary *_toolDocument; } @end @implementation DYRenderer +#include "DYToolRender.inc.h" - (instancetype)init{if((self=[super init])){_previewLock=[NSObject new];_devices=[NSMutableDictionary new];_luts=[NSMutableDictionary new];_preparedLUTs=[NSMutableDictionary new];_activeLUTPaths=[NSSet new];_lutPreparationQueue=dispatch_queue_create("com.dayu.color.lut-upload",DISPATCH_QUEUE_SERIAL);dispatch_set_target_queue(_lutPreparationQueue,dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0));_tables=[DYColorTables new];}return self;} - (void)dealloc{[_devices release];[_luts release];[_preparedLUTs release];[_activeLUTPaths release];dispatch_release(_lutPreparationQueue);[_tables release];[_preview release];[_lookLUTPreview release];[_previewLock release];[super dealloc];} - (void)trimPreparedLUTsKeeping:(NSString *)path { @@ -91,7 +96,7 @@ static void bypassIdleSkin(DYUniforms *u){ NSURL*url=[[NSBundle bundleForClass:self.class]URLForResource:@"default" withExtension:@"metallib"]; idlib=[d newLibraryWithURL:url error:err];if(!lib){[d release];return nil;} idq=[d newCommandQueue];entry=[NSMutableDictionary dictionaryWithDictionary:@{@"device":d,@"library":lib,@"queue":q,@"pipelines":[NSMutableDictionary dictionary]}]; - for(NSString*fn in @[@"dyUnpremultiply",@"dyWhitesSceneStatistics",@"dyLUTExportKernel",@"dyInputAnalysis",@"dyColorManagement"]){idf=[lib newFunctionWithName:fn];if(!f){fail(err,[fn stringByAppendingString:@" 缺失"]);[lib release];[q release];[d release];return nil;}idp=[d newComputePipelineStateWithFunction:f error:err];[f release];if(!p){[lib release];[q release];[d release];return nil;}entry[fn]=p;[p release];} + for(NSString*fn in @[@"dyUnpremultiply",@"dyWhitesSceneStatistics",@"dyLUTExportKernel",@"dyInputAnalysis",@"dyColorManagement",@"dyToolBlend",@"dyToolSkin"]){idf=[lib newFunctionWithName:fn];if(!f){fail(err,[fn stringByAppendingString:@" 缺失"]);[lib release];[q release];[d release];return nil;}idp=[d newComputePipelineStateWithFunction:f error:err];[f release];if(!p){[lib release];[q release];[d release];return nil;}entry[fn]=p;[p release];} float identity[32];for(int z=0;z<2;z++)for(int y=0;y<2;y++)for(int x=0;x<2;x++){int i=((z*2+y)*2+x)*4;identity[i]=x;identity[i+1]=y;identity[i+2]=z;identity[i+3]=1;}idneutral=texture3D(d,identity,2);if(!neutral){fail(err,@"无法分配中性 LUT");return nil;}entry[@"identity"]=neutral; // Preparing before the first frame may use registry 0. Reuse those pipelines // when the host subsequently supplies that device's actual registry ID. @@ -121,7 +126,8 @@ static void bypassIdleSkin(DYUniforms *u){ idh=[_tables hslForDevice:d uniforms:u],w=[_tables whiteBalanceForDevice:d uniforms:u],g=[_tables gradingForDevice:d uniforms:u];if(!h||!w||!g){fail(err,_tables.lastError?:@"颜色查表构建失败");return nil;}[ts addObjectsFromArray:@[h,w,g]];return ts; } - (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths error:(NSError**)err{return [self renderSource:src destination:dst uniforms:u paths:paths spider:nil error:err];} -- (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData *)spider error:(NSError**)err{@synchronized(self){@autoreleasepool{ +- (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData *)spider error:(NSError**)err{return [self renderLegacy:src destination:dst uniforms:u paths:paths spider:spider masks:@{} error:err];} +- (BOOL)renderLegacy:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData *)spider masks:(NSDictionary*)masks error:(NSError**)err{@synchronized(self){@autoreleasepool{ if(spider.length&&!DYSpiderMeshIsValid(spider))return fail(err,@"蜘蛛盘数据无效"); if(u.primarySectionEnabled<.5){u.inputSectionEnabled=0;u.cm.basisEnabled=0;u.cm.outputEnabled=0;} @@ -138,13 +144,14 @@ static void bypassIdleSkin(DYUniforms *u){ } if([e[@"spiderActive"]boolValue]){spiderBuffer=e[@"spiderBuffer"];spiderSize={ [e[@"spiderHues"]intValue],[e[@"spiderRings"]intValue]};} } - NSMutableDictionary*ps=e[@"pipelines"];NSNumber*format=@(output.pixelFormat);idpipeline=ps[format];if(!pipeline){MTLRenderPipelineDescriptor*p=[MTLRenderPipelineDescriptor new];p.vertexFunction=[e[@"library"]newFunctionWithName:@"dyVertex"];p.fragmentFunction=[e[@"library"]newFunctionWithName:@"dyFragment"];p.colorAttachments[0].pixelFormat=output.pixelFormat;pipeline=[d newRenderPipelineStateWithDescriptor:p error:err];[p.vertexFunction release];[p.fragmentFunction release];[p release];if(!pipeline)return NO;ps[format]=pipeline;[pipeline release];} + DYToolMaskHeader maskHeader{};idmaskBuffer=[self maskBuffer:masks tile:src device:d header:&maskHeader];BOOL hasMasks=maskHeader.count>0; + NSMutableDictionary*ps=e[@"pipelines"];NSString*format=[NSString stringWithFormat:@"%lu-%d",(unsigned long)output.pixelFormat,hasMasks];idpipeline=ps[format];if(!pipeline){MTLRenderPipelineDescriptor*p=[MTLRenderPipelineDescriptor new];p.vertexFunction=[e[@"library"]newFunctionWithName:@"dyVertex"];p.fragmentFunction=[e[@"library"]newFunctionWithName:hasMasks?@"dyMaskedFragment":@"dyFragment"];p.colorAttachments[0].pixelFormat=output.pixelFormat;pipeline=[d newRenderPipelineStateWithDescriptor:p error:err];[p.vertexFunction release];[p.fragmentFunction release];[p release];if(!pipeline)return NO;ps[format]=pipeline;[pipeline release];} MTLTextureDescriptor*td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:input.width height:input.height mipmapped:NO];td.storageMode=MTLStorageModePrivate;td.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;idstraight=[d newTextureWithDescriptor:td];if(!straight)return fail(err,@"无法分配调色缓冲区"); idcb=[e[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyUnpremultiply"]];[ce setTexture:input atIndex:0];[ce setTexture:straight atIndex:1];[ce dispatchThreads:MTLSizeMake(input.width,input.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding]; if(useCM&&!identityCM(u)&&u.cm.mix>0){ DayuRenderParams cm=DYCMRender(u.cm);cm.stages=(cm.stages&~1)|(u.inputSectionEnabled>.5?1:0); if(cm.stages){idconverted=[d newTextureWithDescriptor:td];if(!converted){[straight release];return fail(err,@"无法分配 CST 缓冲区");} - ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyColorManagement"]];[ce setTexture:straight atIndex:0];[ce setTexture:converted atIndex:1];[ce setBytes:&cm length:sizeof(cm) atIndex:0];[ce setBytes:&u.cm.mix length:4 atIndex:1];[ce dispatchThreads:MTLSizeMake(input.width,input.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[straight release];straight=converted; + ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyColorManagement"]];[ce setTexture:straight atIndex:0];[ce setTexture:converted atIndex:1];[ce setBytes:&cm length:sizeof(cm) atIndex:0];[ce setBytes:&u.cm.mix length:4 atIndex:1];[ce dispatchThreads:MTLSizeMake(input.width,input.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];if(hasMasks){idblended=[d newTextureWithDescriptor:td];maskHeader.section=0;maskHeader.premultiplied=0;[self encodeBlend:straight after:converted output:blended masks:maskBuffer header:maskHeader entry:e commands:cb];[converted release];converted=blended;}[straight release];straight=converted; } } float level=.5;idscene=[d newBufferWithBytes:&level length:4 options:MTLResourceStorageModeShared]; @@ -155,7 +162,7 @@ static void bypassIdleSkin(DYUniforms *u){ if(src.imageOrigin==kFxImageOrigin_BOTTOM_LEFT){top=1-top;bottom=1-bottom;} DYVertex2D vs[]={{{w/2,-h/2},{r,bottom}},{{-w/2,-h/2},{l,bottom}},{{w/2,h/2},{r,top}},{{-w/2,h/2},{l,top}}}; if(dst.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)for(int i=0;i<4;i++)vs[i].position.y=-vs[i].position.y; - vector_uint2 vp={(unsigned)output.width,(unsigned)output.height};[re setVertexBytes:vs length:sizeof(vs) atIndex:0];[re setVertexBytes:&vp length:sizeof(vp) atIndex:1];[re setViewport:(MTLViewport){0,0,w,h,0,1}];[re setFragmentTexture:straight atIndex:0];for(NSUInteger i=0;ia=[self actionAPI];if(!a)return;[a startAction:self];NSArray *layers=nil;@try{layers=[DYReadTools(_manager,a.currentTime).document[@"layers"]copy];}@finally{[a endAction:self];} + NSMutableArray *order=[NSMutableArray array];NSMutableDictionary *numbers=[NSMutableDictionary dictionary]; + for(NSDictionary *node in layers){NSString *ID=node[@"id"],*type=node[@"type"];[order addObject:ID];NSInteger number=MAX(1,[numbers[type]integerValue])+1;numbers[type]=@(number); + DYInspector *view=_stackViews[ID];if(!view){DYToolManager *manager=[[[DYToolManager alloc]initWithHost:_manager node:node]autorelease];view=[[[DYInspector alloc]initWithAPIManager:manager renderer:_renderer]autorelease];_stackViews[ID]=view;[_document addSubview:view];} + if(view->_cards.count){NSDictionary *section=view->_cards[0][@"section"];[view->_cards[0][@"header"]setTitle:[NSString stringWithFormat:@"%@ %ld",section[@"title"],(long)number]];} + [view refresh];[view setNeedsLayout:YES]; + } + for(NSString *ID in [[_stackViews.allKeys copy]autorelease])if(![order containsObject:ID]){[_stackViews[ID]removeFromSuperview];[_stackViews removeObjectForKey:ID];} + [_stackOrder release];_stackOrder=[order copy];[layers release];[self setNeedsLayout:YES]; +} +- (void)toolMask:(NSButton*)sender{if(sender.tag<0||sender.tag>=_cards.count)return;[(DYToolMaskPanel*)_cards[sender.tag][@"maskPanel"]addMenu:sender];} +- (void)repeatTool:(NSButton*)sender{ + if(sender.tag<0||sender.tag>=_cards.count)return;idhost=_embedded?[(DYToolManager*)_manager host]:_manager;ida=[host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self]; + @try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(host,a.currentTime).document);NSMutableArray *layers=doc[@"layers"];if(layers.count>=DYToolLimit){[self showError:@"最多可添加 32 个独立工具层。"];return;}NSDictionary *node=DYNewTool(_cards[sender.tag][@"section"][@"key"]);if(!node)return;[layers addObject:node];idundo=[host apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:@"再加一层初始化工具"];DYWriteTools(host,doc,a.currentTime);[undo endUndoGroup];}@finally{[a endAction:self];}[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:host]; +} +- (void)removeTool:(id)sender{if(!_embedded)return;idhost=[(DYToolManager*)_manager host];ida=[host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(host,a.currentTime).document);NSMutableArray *layers=doc[@"layers"];NSDictionary *node=DYToolWithID(doc,[(DYToolManager*)_manager nodeID]);if(!node)return;[layers removeObject:node];idundo=[host apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:@"删除独立工具层"];DYWriteTools(host,doc,a.currentTime);[undo endUndoGroup];}@finally{[a endAction:self];}dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:host];});} diff --git a/大鱼调色/Plugin/DYToolRender.inc.h b/大鱼调色/Plugin/DYToolRender.inc.h new file mode 100644 index 0000000..0b9e9ac --- /dev/null +++ b/大鱼调色/Plugin/DYToolRender.inc.h @@ -0,0 +1,43 @@ +// Included in DYRenderer; all calls execute under its per-instance recursive lock. +- (id)maskBuffer:(NSDictionary*)groups tile:(FxImageTile*)tile device:(id)device header:(DYToolMaskHeader*)h { + std::vector entries;FxRect image=tile.imagePixelBounds,bounds=tile.tilePixelBounds; + float w=image.right-image.left,ht=image.top-image.bottom;BOOL bottom=tile.imageOrigin==kFxImageOrigin_BOTTOM_LEFT; + h->offsetX=(bounds.left-image.left)/w;h->scaleX=(bounds.right-bounds.left)/w; + h->offsetY=bottom?(image.top-bounds.bottom)/ht:(image.top-bounds.top)/ht;h->scaleY=(bottom?-1:1)*(bounds.top-bounds.bottom)/ht; + h->premultiplied=1; + for(NSString *type in groups){NSInteger section=[DYToolTypes()indexOfObject:type];if(section==NSNotFound)continue; + for(NSDictionary *m in groups[type]){if(![m[@"enabled"]boolValue])continue;DYToolMaskEntry entry{};entry.section=(int)section;entry.combine=[m[@"combine"]intValue];[m[@"parameters"]getBytes:&entry.mask.parameters length:sizeof(DYMaskParameters)];entry.mask.parameters.imageAspect=w/ht;NSData *nodes=m[@"nodes"];entry.mask.path=dyFlattenMask((const DYBezierNode*)nodes.bytes,nodes.length/sizeof(DYBezierNode));entries.push_back(entry);} + }h->count=(unsigned)entries.size();if(entries.empty())entries.push_back({});return [[device newBufferWithBytes:entries.data() length:entries.size()*sizeof(DYToolMaskEntry) options:MTLResourceStorageModeShared]autorelease]; +} +- (void)encodeBlend:(id)before after:(id)after output:(id)output masks:(id)masks header:(DYToolMaskHeader)h entry:(NSDictionary*)entry commands:(id)commands { + idencoder=[commands computeCommandEncoder];[encoder setComputePipelineState:entry[@"dyToolBlend"]];[encoder setTexture:before atIndex:0];[encoder setTexture:after atIndex:1];[encoder setTexture:output atIndex:2];[encoder setBuffer:masks offset:0 atIndex:0];[encoder setBytes:&h length:sizeof(h) atIndex:1];[encoder dispatchThreads:MTLSizeMake(output.width,output.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[encoder endEncoding]; +} +- (BOOL)copyTile:(FxImageTile*)source to:(FxImageTile*)dest entry:(NSMutableDictionary*)e error:(NSError**)error { + iddevice=e[@"device"];ida=[source metalTextureForDevice:device],b=[dest metalTextureForDevice:device]; + NSMutableDictionary *pipelines=e[@"pipelines"];NSString *key=[NSString stringWithFormat:@"copy-%lu",(unsigned long)b.pixelFormat];idpipeline=pipelines[key]; + if(!pipeline){MTLRenderPipelineDescriptor *desc=[MTLRenderPipelineDescriptor new];desc.vertexFunction=[e[@"library"]newFunctionWithName:@"dyVertex"];desc.fragmentFunction=[e[@"library"]newFunctionWithName:@"dyToolCopyFragment"];desc.colorAttachments[0].pixelFormat=b.pixelFormat;pipeline=[device newRenderPipelineStateWithDescriptor:desc error:error];[desc.vertexFunction release];[desc.fragmentFunction release];[desc release];if(!pipeline)return NO;pipelines[key]=pipeline;[pipeline release];} + FxRect s=source.tilePixelBounds,t=dest.tilePixelBounds;float width=s.right-s.left,height=s.top-s.bottom,l=(t.left-s.left)/width,r=(t.right-s.left)/width,top=(s.top-t.top)/height,bottom=(s.top-t.bottom)/height; + if(source.imageOrigin==kFxImageOrigin_BOTTOM_LEFT){top=1-top;bottom=1-bottom;} + float w=b.width,h=b.height;DYVertex2D v[]={{{w/2,-h/2},{r,bottom}},{{-w/2,-h/2},{l,bottom}},{{w/2,h/2},{r,top}},{{-w/2,h/2},{l,top}}};if(dest.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)for(auto &vertex:v)vertex.position.y=-vertex.position.y; + vector_uint2 size={(unsigned)b.width,(unsigned)b.height};idcb=[e[@"queue"]commandBuffer];MTLRenderPassDescriptor *pass=[MTLRenderPassDescriptor renderPassDescriptor];pass.colorAttachments[0].texture=b;pass.colorAttachments[0].loadAction=MTLLoadActionDontCare;pass.colorAttachments[0].storeAction=MTLStoreActionStore;idencoder=[cb renderCommandEncoderWithDescriptor:pass];[encoder setRenderPipelineState:pipeline];[encoder setVertexBytes:v length:sizeof(v) atIndex:0];[encoder setVertexBytes:&size length:sizeof(size) atIndex:1];[encoder setFragmentTexture:a atIndex:0];[encoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];[encoder endEncoding];[cb commit];[cb waitUntilCompleted];return cb.status==MTLCommandBufferStatusCompleted?YES:fail(error,cb.error.localizedDescription); +} +- (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools error:(NSError**)error {@synchronized(self){@autoreleasepool{ + if(!tools)return [self renderLegacy:src destination:dst uniforms:u paths:paths spider:spider masks:@{} error:error];if(!DYValidToolDocument(tools))return fail(error,@"工具或蒙版数据损坏,未更改原工程"); + NSArray *layers=tools[@"layers"];BOOL active=NO;for(NSDictionary *n in layers)active|=!DYToolIsNeutral(n); + if(!active)return [self renderLegacy:src destination:dst uniforms:u paths:paths spider:spider masks:tools[@"baseMasks"] error:error]; + NSMutableDictionary *entry=[self device:dst.deviceRegistryID error:error];if(!entry)return NO;idd=entry[@"device"];idinput=[src metalTextureForDevice:d]; + MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:input.width height:input.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageRenderTarget|MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite; + idcurrent=[d newTextureWithDescriptor:desc];if(!current)return fail(error,@"无法分配工具图层缓冲区");DYExportTile *tile=[[[DYExportTile alloc]initWithTexture:current registry:d.registryID]autorelease];[tile setBounds:src.tilePixelBounds origin:src.imageOrigin];[current release]; + if(![self renderLegacy:src destination:tile uniforms:u paths:paths spider:spider masks:tools[@"baseMasks"] error:error])return NO; + for(NSDictionary *node in layers){if(DYToolIsNeutral(node))continue;DYUniforms layer=DYToolUniforms(node);NSString *type=node[@"type"]; + idnext=[d newTextureWithDescriptor:desc];if(!next)return fail(error,@"无法分配新增工具缓冲区");DYExportTile *nextTile=[[[DYExportTile alloc]initWithTexture:next registry:d.registryID]autorelease];[nextTile setBounds:src.tilePixelBounds origin:src.imageOrigin];[next release]; + if([type isEqual:@"skin"]){idcb=[entry[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];[ce setComputePipelineState:entry[@"dyToolSkin"]];[ce setTexture:[tile metalTextureForDevice:d] atIndex:0];[ce setTexture:input atIndex:1];[ce setTexture:[nextTile metalTextureForDevice:d] atIndex:2];[ce setBytes:&layer length:sizeof(layer) atIndex:0];[ce dispatchThreads:MTLSizeMake(input.width,input.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription); + if([node[@"masks"]count]){idblend=[d newTextureWithDescriptor:desc];DYToolMaskHeader h{};h.section=3;idbuffer=[self maskBuffer:@{type:node[@"masks"]} tile:tile device:d header:&h];cb=[entry[@"queue"]commandBuffer];[self encodeBlend:[tile metalTextureForDevice:d] after:[nextTile metalTextureForDevice:d] output:blend masks:buffer header:h entry:entry commands:cb];[cb commit];[cb waitUntilCompleted];DYExportTile *blended=[[[DYExportTile alloc]initWithTexture:blend registry:d.registryID]autorelease];[blended setBounds:src.tilePixelBounds origin:src.imageOrigin];[blend release];nextTile=blended;if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription);} + }else if(![self renderLegacy:tile destination:nextTile uniforms:layer paths:node[@"paths"] spider:node[@"spider"] masks:@{type:node[@"masks"]} error:error])return NO; + tile=nextTile; + }return [self copyTile:tile to:dst entry:entry error:error]; + }}} +- (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools error:(NSError**)error {@synchronized(self){ + for(NSArray *masks in [tools[@"baseMasks"]allValues])if(masks.count)return fail(error,@"当前调色含空间蒙版或跟踪,Cube 无法保存这些信息。请先保存完整预设,或移除蒙版后导出。");for(NSDictionary *node in tools[@"layers"])if([node[@"masks"]count])return fail(error,@"新增工具含蒙版,无法完整导出为 Cube。请保存完整预设。"); + _toolDocument=tools;BOOL ok=NO;@try{ok=[self exportLUT:url uniforms:u paths:paths spider:spider error:error];}@finally{_toolDocument=nil;}return ok; +}} diff --git a/大鱼调色/Plugin/DYToolState.h b/大鱼调色/Plugin/DYToolState.h new file mode 100644 index 0000000..349eaf9 --- /dev/null +++ b/大鱼调色/Plugin/DYToolState.h @@ -0,0 +1,33 @@ +#pragma once +#import "DYModel.h" +#include "MaskCore/DYMaskOperator.h" + +enum { DYToolsParameterID=9002, DYCanvasSessionParameterID=9003, DYToolLimit=32, DYToolMaskLimit=16, DYToolKeyLimit=16384 }; +// Immutable property-list author state. Host float IDs and the legacy ABI stay fixed. +@interface DYToolDocument : NSObject +@property(nonatomic,copy) NSDictionary *document; +@end +NSArray *DYToolTypes(void); +NSDictionary *DYToolSection(NSString *type); +NSDictionary *DYNewTool(NSString *type); +NSDictionary *DYNewMask(NSInteger kind); +BOOL DYValidToolDocument(NSDictionary *document); +BOOL DYValidToolMask(NSDictionary *mask); +NSMutableDictionary *DYMutablePlist(NSDictionary *value); +DYToolDocument *DYReadTools(id manager,CMTime time); +BOOL DYWriteTools(id manager,NSDictionary *document,CMTime time); +NSArray *DYMasksForTool(NSDictionary *document,NSString *nodeID); +NSDictionary *DYToolWithID(NSDictionary *document,NSString *nodeID); +BOOL DYSetToolMasks(NSMutableDictionary *document,NSString *nodeID,NSArray *masks); +DYMaskParameters DYMaskAtTime(NSDictionary *mask,CMTime time); +NSDictionary *DYMaskKey(CMTime time,DYMaskParameters parameters,BOOL manual,float confidence); +BOOL DYMergeTracking(NSMutableDictionary *mask,NSArray *samples); +NSDictionary *DYToolRenderSnapshot(NSDictionary *document,CMTime time); +DYUniforms DYToolUniforms(NSDictionary *node); +BOOL DYToolIsNeutral(NSDictionary *node); +// Routes an existing native panel to a UUID, batching edits into one host write. +@interface DYToolManager : NSObject +@property(nonatomic,readonly) id host; +@property(nonatomic,readonly) NSString *nodeID,*type; +- (instancetype)initWithHost:(id)host node:(NSDictionary *)node; +@end diff --git a/大鱼调色/Plugin/DYToolState.mm b/大鱼调色/Plugin/DYToolState.mm new file mode 100644 index 0000000..c8e35d7 --- /dev/null +++ b/大鱼调色/Plugin/DYToolState.mm @@ -0,0 +1,78 @@ +#import "DYToolState.h" +#include "DYSpiderState.h" +#include +#import + +NSArray *DYToolTypes(void){return @[@"primary",@"spider",@"base",@"skin",@"look",@"hsl",@"curve",@"grading",@"primaries",@"levels",@"blackwhite",@"balance"];} +NSDictionary *DYToolSection(NSString *type){for(NSDictionary *s in DYSections())if([s[@"key"]isEqual:type])return s;return nil;} +NSMutableDictionary *DYMutablePlist(NSDictionary *value){if(!value)return [NSMutableDictionary dictionary];NSData *data=[NSPropertyListSerialization dataWithPropertyList:value format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];return [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListMutableContainersAndLeaves format:NULL error:nil];} +static NSDictionary *DYEmptyTools(){return @{@"schema":@1,@"layers":@[],@"baseMasks":@{}};} +static BOOL finiteNumber(id v){return [v isKindOfClass:NSNumber.class]&&std::isfinite([v doubleValue]);} +static BOOL validID(id v){return [v isKindOfClass:NSString.class]&&[[[NSUUID alloc]initWithUUIDString:v]autorelease]!=nil;} +static NSData *parameterData(DYMaskParameters p){return [NSData dataWithBytes:&p length:sizeof(p)];} +static BOOL readParameters(id data,DYMaskParameters *p){if(![data isKindOfClass:NSData.class]||[data length]!=sizeof(*p))return NO;[data getBytes:p length:sizeof(*p)];return dyValidMaskParameters(*p);} +static CMTime keyTime(NSDictionary *key){return CMTimeMakeWithEpoch([key[@"value"]longLongValue],[key[@"scale"]intValue],[key[@"epoch"]longLongValue]);} +NSDictionary *DYNewMask(NSInteger kind){if(kind<0||kind>5)return nil;DYMaskParameters p=dyDefaultMaskParameters();p.kind=(DYMaskKind)kind;p.width=.5;p.height=.5;p.sourceStage=DYMaskSourceOriginal;if(kind==DYMaskHSLKey)p.flags=DYMaskHueEnabled;NSData *nodes=[NSData data];if(kind==DYMaskBezier){DYBezierNode n[4]={};float x[4]={-.5,.5,.5,-.5},y[4]={-.5,-.5,.5,.5};for(int i=0;i<4;i++)n[i]={x[i],y[i],x[i],y[i],x[i],y[i]};nodes=[NSData dataWithBytes:n length:sizeof(n)];}return @{@"id":NSUUID.UUID.UUIDString,@"enabled":@YES,@"combine":@0,@"parameters":parameterData(p),@"nodes":nodes,@"keys":@[]};} +NSDictionary *DYNewTool(NSString *type){if(![DYToolTypes()containsObject:type])return nil;return @{@"id":NSUUID.UUID.UUIDString,@"type":type,@"values":@{},@"paths":@{},@"spiderLinked":@YES,@"masks":@[]};} +BOOL DYValidToolMask(NSDictionary *mask){ + if(![mask isKindOfClass:NSDictionary.class]||!validID(mask[@"id"])||!finiteNumber(mask[@"enabled"])||!finiteNumber(mask[@"combine"])||[mask[@"combine"]integerValue]<0||[mask[@"combine"]integerValue]>2)return NO; + DYMaskParameters p;if(!readParameters(mask[@"parameters"],&p))return NO;NSData *nodes=mask[@"nodes"];if(![nodes isKindOfClass:NSData.class]||nodes.length%sizeof(DYBezierNode)||nodes.length>32*sizeof(DYBezierNode))return NO; + const float *n=(const float*)nodes.bytes;for(NSUInteger i=0;i1000)return NO; + NSArray *keys=mask[@"keys"];if(![keys isKindOfClass:NSArray.class]||keys.count>DYToolKeyLimit)return NO;CMTime last=kCMTimeInvalid; + for(NSDictionary *k in keys){if(![k isKindOfClass:NSDictionary.class]||!finiteNumber(k[@"value"])||!finiteNumber(k[@"scale"])||!finiteNumber(k[@"epoch"])||!finiteNumber(k[@"manual"])||!finiteNumber(k[@"confidence"])||[k[@"confidence"]doubleValue]<0||[k[@"confidence"]doubleValue]>1)return NO;CMTime t=keyTime(k);DYMaskParameters q;if(!CMTIME_IS_NUMERIC(t)||!readParameters(k[@"parameters"],&q)||q.kind!=p.kind||(CMTIME_IS_NUMERIC(last)&&(last.epoch!=t.epoch||CMTimeCompare(last,t)>=0)))return NO;last=t;}return YES; +} +static BOOL validMasks(id masks,NSMutableSet *ids){if(![masks isKindOfClass:NSArray.class]||[masks count]>DYToolMaskLimit)return NO;for(NSDictionary *m in masks){if(!DYValidToolMask(m)||[ids containsObject:m[@"id"]])return NO;[ids addObject:m[@"id"]];}return YES;} +BOOL DYValidToolDocument(NSDictionary *doc){ + if(![doc isKindOfClass:NSDictionary.class]||![doc[@"schema"]isEqual:@1]||![doc[@"layers"]isKindOfClass:NSArray.class]||[doc[@"layers"]count]>DYToolLimit||![doc[@"baseMasks"]isKindOfClass:NSDictionary.class]||[doc[@"baseMasks"]count]>DYToolTypes().count)return NO; + NSMutableSet *ids=[NSMutableSet set];for(NSString *key in doc[@"baseMasks"]){if(![DYToolTypes()containsObject:key]||!validMasks(doc[@"baseMasks"][key],ids))return NO;} + NSMutableDictionary *descriptors=[NSMutableDictionary dictionary];for(NSDictionary *d in DYDescriptors())descriptors[d[@"key"]]=d; + for(NSDictionary *node in doc[@"layers"]){if(![node isKindOfClass:NSDictionary.class]||!validID(node[@"id"])||[ids containsObject:node[@"id"]]||![DYToolTypes()containsObject:node[@"type"]]||![node[@"values"]isKindOfClass:NSDictionary.class]||[node[@"values"]count]>descriptors.count||![node[@"paths"]isKindOfClass:NSDictionary.class]||[node[@"paths"]count]>6||!validMasks(node[@"masks"],ids))return NO;[ids addObject:node[@"id"]]; + for(NSString *key in node[@"values"]){NSDictionary *d=descriptors[key];id v=node[@"values"][key];if(!d||!finiteNumber(v)||[v doubleValue]<[d[@"min"]doubleValue]||[v doubleValue]>[d[@"max"]doubleValue]||(d[@"values"]&&![d[@"values"]containsObject:@((int)llround([v doubleValue]))]))return NO;} + for(id key in node[@"paths"]){id p=node[@"paths"][key];if(![@[@"input",@"look0",@"look1",@"look2",@"look3",@"look4"]containsObject:key]||![p isKindOfClass:NSString.class]||[p length]>8192)return NO;}if(node[@"spider"]&&(![node[@"spider"]isKindOfClass:NSData.class]||!DYSpiderMeshIsValid(node[@"spider"])))return NO; + }return YES; +} +@implementation DYToolDocument ++ (BOOL)supportsSecureCoding{return YES;} +- (instancetype)init{if((self=[super init]))_document=[DYEmptyTools()copy];return self;} +- (void)dealloc{[_document release];[super dealloc];} +- (void)setDocument:(NSDictionary *)d{if(!DYValidToolDocument(d))return;NSData *b=[NSPropertyListSerialization dataWithPropertyList:d format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];NSDictionary *immutable=[NSPropertyListSerialization propertyListWithData:b options:NSPropertyListImmutable format:NULL error:nil];[_document release];_document=[immutable retain];} +- (void)encodeWithCoder:(NSCoder*)c{[c encodeObject:_document forKey:@"document"];} +- (instancetype)initWithCoder:(NSCoder*)c{if((self=[self init])){NSDictionary *d=[c decodeObjectOfClasses:[NSSet setWithObjects:NSDictionary.class,NSArray.class,NSString.class,NSNumber.class,NSData.class,nil] forKey:@"document"];if(!DYValidToolDocument(d)){[self release];return nil;}self.document=d;}return self;} +- (id)copyWithZone:(NSZone*)zone{DYToolDocument *v=[[[self class]allocWithZone:zone]init];v.document=_document;return v;} +- (BOOL)isEqual:(id)o{return [o isKindOfClass:DYToolDocument.class]&&[_document isEqual:[o document]];} +- (NSUInteger)hash{return _document.hash;} +- (id)interpolateBetween:(id)other withWeight:(float)weight{return [[self copy]autorelease];} +@end +DYToolDocument *DYReadTools(idm,CMTime t){DYToolDocument *d=nil;[[(id)m apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getCustomParameterValue:&d fromParameter:DYToolsParameterID atTime:t];return [d isKindOfClass:DYToolDocument.class]?d:[[[DYToolDocument alloc]init]autorelease];} +BOOL DYWriteTools(idm,NSDictionary *d,CMTime t){if(!DYValidToolDocument(d))return NO;DYToolDocument *v=[[[DYToolDocument alloc]init]autorelease];v.document=d;return [[m apiForProtocol:@protocol(FxParameterSettingAPI_v6)]setCustomParameterValue:v toParameter:DYToolsParameterID atTime:t];} +NSDictionary *DYToolWithID(NSDictionary *doc,NSString *ID){for(NSDictionary *n in doc[@"layers"])if([n[@"id"]isEqual:ID])return n;return nil;} +NSArray *DYMasksForTool(NSDictionary *doc,NSString *ID){return [ID hasPrefix:@"base:"]?doc[@"baseMasks"][[ID substringFromIndex:5]]?:@[]:DYToolWithID(doc,ID)[@"masks"]?:@[];} +BOOL DYSetToolMasks(NSMutableDictionary *doc,NSString *ID,NSArray *masks){if([ID hasPrefix:@"base:"]){NSString *type=[ID substringFromIndex:5];if(![DYToolTypes()containsObject:type])return NO;doc[@"baseMasks"][type]=masks;}else{NSMutableDictionary *n=(id)DYToolWithID(doc,ID);if(!n)return NO;n[@"masks"]=masks;}return YES;} +DYMaskParameters DYMaskAtTime(NSDictionary *mask,CMTime time){DYMaskParameters p=dyDefaultMaskParameters();readParameters(mask[@"parameters"],&p);NSArray *keys=mask[@"keys"];if(!keys.count||!CMTIME_IS_NUMERIC(time))return p;NSDictionary *left=nil,*right=nil;for(NSDictionary *k in keys){CMTime t=keyTime(k);if(t.epoch!=time.epoch)return p;if(CMTimeCompare(t,time)<=0)left=k;if(CMTimeCompare(t,time)>=0){right=k;break;}}left=left?:right;right=right?:left;DYMaskParameters a,b;readParameters(left[@"parameters"],&a);readParameters(right[@"parameters"],&b);double duration=CMTimeGetSeconds(CMTimeSubtract(keyTime(right),keyTime(left)));float w=duration>0?fmax(0,fmin(1,CMTimeGetSeconds(CMTimeSubtract(time,keyTime(left)))/duration)):0; + // Only temporal geometry/feather/strength interpolate; key selection and levels stay authored. + float *v=&p.centerX,*av=&a.centerX,*bv=&b.centerX;for(int i=0;i<8;i++)v[i]=av[i]+(bv[i]-av[i])*w;return p;} +NSDictionary *DYMaskKey(CMTime t,DYMaskParameters p,BOOL manual,float confidence){return @{@"value":@(t.value),@"scale":@(t.timescale),@"epoch":@(t.epoch),@"parameters":parameterData(p),@"manual":@(manual),@"confidence":@(confidence)};} +BOOL DYMergeTracking(NSMutableDictionary *m,NSArray *samples){if(!samples.count)return YES;NSMutableArray *all=[NSMutableArray array];CMTime lo=keyTime(samples.firstObject),hi=keyTime(samples.lastObject);if(CMTimeCompare(lo,hi)>0)std::swap(lo,hi);for(NSDictionary *key in m[@"keys"])if([key[@"manual"]boolValue]||CMTimeCompare(keyTime(key),lo)<0||CMTimeCompare(keyTime(key),hi)>0)[all addObject:key];for(NSDictionary *key in samples){BOOL manual=NO;for(NSDictionary *old in all)if(CMTimeCompare(keyTime(old),keyTime(key))==0){manual=YES;break;}if(!manual)[all addObject:key];}[all sortUsingComparator:^NSComparisonResult(NSDictionary *a,NSDictionary *b){return (NSComparisonResult)CMTimeCompare(keyTime(a),keyTime(b));}];NSMutableDictionary *candidate=DYMutablePlist(m);candidate[@"keys"]=all;if(!DYValidToolMask(candidate))return NO;m[@"keys"]=all;return YES;} +NSDictionary *DYToolRenderSnapshot(NSDictionary *doc,CMTime t){NSMutableDictionary *out=DYMutablePlist(doc);NSMutableArray *groups=[NSMutableArray arrayWithArray:[out[@"baseMasks"]allValues]];for(NSDictionary *n in out[@"layers"])[groups addObject:n[@"masks"]];for(NSArray *masks in groups)for(NSMutableDictionary *m in masks){m[@"parameters"]=parameterData(DYMaskAtTime(m,t));m[@"keys"]=@[];}return out;} +DYUniforms DYToolUniforms(NSDictionary *node){DYUniforms u;DYDefaultUniforms(&u);NSString *type=node[@"type"];for(NSDictionary *s in DYSections())for(NSDictionary *d in DYDescriptors())if([d[@"pid"]isEqual:s[@"enabled"]])*(float*)((uint8_t*)&u+[d[@"offset"]unsignedIntegerValue])=0;u.primarySectionEnabled=0;u.cm.configured=-1;u.inputProfile=u.preLUTStrength=0;u.skinProtection.x=0; + NSArray *parts=[type isEqual:@"primary"]?@[@"input",@"primary",@"output"]:[type isEqual:@"base"]?@[@"base",@"color"]:@[type];for(NSString *part in parts){NSDictionary *s=DYToolSection(part);for(NSDictionary *d in DYDescriptors())if([d[@"pid"]isEqual:s[@"enabled"]])*(float*)((uint8_t*)&u+[d[@"offset"]unsignedIntegerValue])=1;} + if([type isEqual:@"primary"]){u.primarySectionEnabled=1;u.cm.configured=1;u.cm.inputTransfer=u.cm.outputTransfer;u.cm.inputGamut=u.cm.outputGamut;} + for(NSDictionary *d in DYDescriptors()){NSNumber *v=node[@"values"][d[@"key"]];if(v&&[d[@"offset"]integerValue]>=0)*(float*)((uint8_t*)&u+[d[@"offset"]unsignedIntegerValue])=v.floatValue;}return u;} +BOOL DYToolIsNeutral(NSDictionary *node){if([node[@"type"]isEqual:@"spider"]&&[node[@"spider"]length]){auto mesh=DYSpiderMesh(node[@"spider"]);for(float v:dy::meshSamples(mesh))if(v!=0)return NO;}if([node[@"paths"]count])return NO;for(NSDictionary *d in DYDescriptors()){NSNumber *v=node[@"values"][d[@"key"]];if(v&&v.floatValue!=[d[@"default"]floatValue])return NO;}return YES;} + +@implementation DYToolManager { + id _host;NSString *_nodeID,*_type;NSInteger _depth;CMTime _time;NSMutableDictionary *_pending;DYInspectorToken *_token; +} +@synthesize host=_host,nodeID=_nodeID,type=_type; +- (instancetype)initWithHost:(id)h node:(NSDictionary*)n{if((self=[super init])){_host=h;_nodeID=[n[@"id"]copy];_type=[n[@"type"]copy];}return self;} +- (void)dealloc{[_nodeID release];[_type release];[_pending release];[_token release];[super dealloc];} +- (id)apiForProtocol:(Protocol*)p{if(protocol_isEqual(p,@protocol(FxParameterRetrievalAPI_v6))||protocol_isEqual(p,@protocol(FxParameterSettingAPI_v6))||protocol_isEqual(p,@protocol(FxCustomParameterActionAPI_v4)))return self;return [_host apiForProtocol:p];} +- (void)startAction:(id)sender{if(_depth++==0){[[_host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)]startAction:sender];_time=[(id)[_host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)]currentTime];[_pending release];_pending=[DYMutablePlist(DYReadTools(_host,_time).document)retain];}} +- (void)endAction:(id)sender{if(_depth<=0)return;if(--_depth==0){NSDictionary *original=DYReadTools(_host,_time).document;if(![_pending isEqual:original])DYWriteTools(_host,_pending,_time);if(_token)[[_host apiForProtocol:@protocol(FxParameterSettingAPI_v6)]setCustomParameterValue:_token toParameter:DYInspectorParameterID atTime:_time];[_token release];_token=nil;[[_host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)]endAction:sender];}} +- (CMTime)currentTime{return _time;} +- (NSDictionary*)node{return DYToolWithID(_pending?:DYReadTools(_host,_time).document,_nodeID);} +- (BOOL)getFloatValue:(double*)out fromParameter:(UInt32)pid atTime:(CMTime)t{NSDictionary *n=[self node];DYUniforms u=DYToolUniforms(n?:@{@"type":_type});for(NSDictionary *d in DYDescriptors())if([d[@"pid"]unsignedIntValue]==pid){*out=[d[@"offset"]integerValue]>=0?*(float*)((uint8_t*)&u+[d[@"offset"]unsignedIntegerValue]):[d[@"default"]doubleValue];return YES;}return NO;} +- (BOOL)setFloatValue:(double)v toParameter:(UInt32)pid atTime:(CMTime)t{if(!_depth||!std::isfinite(v))return NO;NSMutableDictionary *n=(id)[self node];if(!n)return NO;for(NSDictionary *d in DYDescriptors())if([d[@"pid"]unsignedIntValue]==pid){n[@"values"][d[@"key"]]=@(v);return YES;}return NO;} +- (BOOL)getCustomParameterValue:(id*)out fromParameter:(UInt32)pid atTime:(CMTime)t{if(pid==DYAssetsParameterID){DYAssetState *a=[[[DYAssetState alloc]init]autorelease];NSDictionary *n=[self node];a.paths=n[@"paths"]?:@{};a.spiderMesh=n[@"spider"];a.spiderLinked=[n[@"spiderLinked"]boolValue];*out=a;return YES;}if(pid==DYInspectorParameterID){DYInspectorToken *global=_token; if(!global)[[_host apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getCustomParameterValue:&global fromParameter:pid atTime:t];DYInspectorToken *local=[[[DYInspectorToken alloc]init]autorelease];NSMutableDictionary *folds=[NSMutableDictionary dictionary];for(NSString *key in global.folds)if([key hasPrefix:[_nodeID stringByAppendingString:@":"]])folds[[key substringFromIndex:_nodeID.length+1]]=global.folds[key];local.folds=folds;*out=local;return YES;}return NO;} +- (BOOL)setCustomParameterValue:(id)v toParameter:(UInt32)pid atTime:(CMTime)t{if(!_depth)return NO;NSMutableDictionary *n=(id)[self node];if(!n)return NO;if(pid==DYAssetsParameterID&&[v isKindOfClass:DYAssetState.class]){n[@"paths"]=DYMutablePlist([v paths]);if([v spiderMesh])n[@"spider"]=[v spiderMesh];else[n removeObjectForKey:@"spider"];n[@"spiderLinked"]=@([v spiderLinked]);return YES;}if(pid==DYInspectorParameterID){DYInspectorToken *old=nil;[[_host apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getCustomParameterValue:&old fromParameter:pid atTime:t];[_token release];_token=old?[old copy]:[DYInspectorToken new];NSMutableDictionary *folds=[[_token.folds mutableCopy]autorelease];for(NSString *key in [v folds])folds[[_nodeID stringByAppendingFormat:@":%@",key]]=[v folds][key];_token.folds=folds;return YES;}return NO;} +@end diff --git a/大鱼调色/Plugin/DYTracking.metal b/大鱼调色/Plugin/DYTracking.metal new file mode 100644 index 0000000..1f07ba0 --- /dev/null +++ b/大鱼调色/Plugin/DYTracking.metal @@ -0,0 +1,51 @@ +#include +using namespace metal; +struct PyramidInfo {int width[5],height[5],offset[5],levels;}; +kernel void dyTrackPyramid(device float*f[[buffer(0)]],constant PyramidInfo&i[[buffer(1)]],constant int&level[[buffer(2)]],uint2 p[[thread_position_in_grid]]) { + int w=i.width[level],h=i.height[level];if(p.x>=uint(w)||p.y>=uint(h))return; + int sw=i.width[level-1],sh=i.height[level-1];float sum=0; + for(int y=-1;y<=1;y++)for(int x=-1;x<=1;x++)sum+=f[i.offset[level-1]+clamp(int(p.y)*2+y,0,sh-1)*sw+clamp(int(p.x)*2+x,0,sw-1)]*(x==0?2.f:1.f)*(y==0?2.f:1.f); + f[i.offset[level]+p.y*w+p.x]=sum/16.f; +} +inline bool inside(float2 p,int w,int h){return all(p>=6.f)&&p.x0;level--){float s=float(1<=0;level--) { + float2 pp=p/float(1<=81)continue; + float2 pos=pp+float2(int(k%9)-4,int(k/9)-4);ref[j]=pixel(a,w,pos);mean+=ref[j]; + gx[j]=.5f*(pixel(a,w,pos+float2(1,0))-pixel(a,w,pos-float2(1,0))); + gy[j]=.5f*(pixel(a,w,pos+float2(0,1))-pixel(a,w,pos-float2(0,1))); + hxx+=gx[j]*gx[j];hxy+=gx[j]*gy[j];hyy+=gy[j]*gy[j]; + } + mean=simd_sum(mean)/81;hxx=simd_sum(hxx);hxy=simd_sum(hxy);hyy=simd_sum(hyy); + float det=hxx*hyy-hxy*hxy;if(det<1e-8f||hxx+hyy<1e-5f)return false; + for(int iteration=0;iteration<20;iteration++) { + if(!inside(q,w,h))return false;float target[3],tm=0; + for(uint j=0;j<3;j++){uint k=lane+j*32;target[j]=k<81?pixel(b,w,q+float2(int(k%9)-4,int(k/9)-4)):0;tm+=target[j];} + tm=simd_sum(tm)/81;float bx=0,by=0,sse=0; + for(uint j=0;j<3;j++)if(lane+j*32<81){float e=ref[j]-mean-target[j]+tm;bx+=gx[j]*e;by+=gy[j]*e;sse+=e*e;} + bx=simd_sum(bx);by=simd_sum(by);sse=simd_sum(sse); + float2 delta=float2(hyy*bx-hxy*by,hxx*by-hxy*bx)/det;if(!all(isfinite(delta))||length(delta)>8)return false; + q+=delta;error=sqrt(sse/81);if(dot(delta,delta)<.0001f)break; + } + if(level>0)q*=2; + } + return inside(q,i.width[0],i.height[0])&&error<.12f; +} +kernel void dyTrackFlow(device const float*prev[[buffer(0)]],device const float*next[[buffer(1)]],device const float2*points[[buffer(2)]],device float4*results[[buffer(3)]],constant PyramidInfo&i[[buffer(4)]],uint gid[[thread_position_in_grid]],uint lane[[thread_index_in_simdgroup]]) { + uint idx=gid/32;float2 p=points[idx],q=0,back=0;float error=0,backError=0; + bool ok=trackFlow(prev,next,i,p,p,q,error,lane); + if(ok)ok=trackFlow(next,prev,i,q,p,back,backError,lane)&&distance(back,p)<=1.1f; + if(lane==0)results[idx]=float4(q,error,ok?1.f:0.f); +} diff --git a/大鱼调色/Plugin/MaskCore/DYMask.h b/大鱼调色/Plugin/MaskCore/DYMask.h new file mode 100644 index 0000000..4db0c56 --- /dev/null +++ b/大鱼调色/Plugin/MaskCore/DYMask.h @@ -0,0 +1,43 @@ +#pragma once +#include "../SpiderCore/DYColorMath.h" + +// Anchors and handles are local to maskX/Y/W/H. Empty path preserves legacy ellipses. +struct DYBezierNode { float x,y,inX,inY,outX,outY; }; +struct DYMaskPath { int count; float x[256],y[256]; }; +inline float dyPathMask(float x,float y,DYREF DYGrade& g,DYREF DYMaskPath& path) { + if(path.count<3)return dyMask(x,y,g); + float aspect=g.imageAspect,dx=(x-g.maskX)*aspect,dy=y-g.maskY; + float c=cos(g.maskAngle),s=sin(g.maskAngle); + float u=(dx*c+dy*s)/(g.maskW*aspect),v=(-dx*s+dy*c)/g.maskH; + bool inside=false;float distance2=1e10f; + // Physical distance in units of the shorter mask axis keeps feathering isotropic. + float shorter=g.maskW*aspectv)!=(by>v))if(u<(bx-ax)*(v-ay)/(by-ay)+ax)inside=!inside; + float ex=(bx-ax)*sx,ey=(by-ay)*sy,px=(u-ax)*sx,py=(v-ay)*sy; + float den=ex*ex+ey*ey,t=den>1e-12f?dyClamp((px*ex+py*ey)/den,0,1):0; + float xx=px-t*ex,yy=py-t*ey,d=xx*xx+yy*yy;if(d +inline DYMaskPath dyFlattenMask(const DYBezierNode* nodes,size_t count) { + DYMaskPath path{};if(!nodes||count<3||count>32)return path; + int steps=std::min(24,int(256/count)); + for(size_t i=0;i +#include +typedef uint32_t DYMaskUInt; +#else +typedef uint DYMaskUInt; +#endif +// Independent versioned mask mathematics. No spatial blur or hidden input transform. +enum DYMaskKind : DYMaskUInt {DYMaskEllipse=0,DYMaskRectangle=1,DYMaskBezier=2,DYMaskLinearGradient=3,DYMaskHSLKey=4,DYMaskLumaKey=5}; +enum DYMaskSourceStage : DYMaskUInt {DYMaskSourceOriginal=0,DYMaskSourceAfterGlobal=1,DYMaskSourceLayerInput=2}; +enum DYMaskFeatherPlacement : DYMaskUInt {DYMaskFeatherInside=0,DYMaskFeatherOutside=1}; +enum : DYMaskUInt {DYMaskInvert=1,DYMaskHueEnabled=2,DYMaskSaturationEnabled=4,DYMaskLightnessEnabled=8,DYMaskFeatherOutsideFlag=16}; +struct DYMaskRange {float low,high,softLow,softHigh;}; +struct DYMaskParameters { + DYMaskUInt version,kind,sourceStage,flags; + float centerX,centerY,width,height,angle,feather,strength,gradientWidth,imageAspect,reserved; + float hueCenterTurns,hueCoreHalfWidth,hueSoftWidth,neutralChromaLow,neutralChromaHigh; + DYMaskRange saturationRange,lightnessRange; + float inputBlack,inputWhite,inputGamma,outputBlack,outputWhite; +}; +struct DYResolvedMask {DYMaskParameters parameters;DYMaskPath path;}; +inline float dyMaskSoftStep(float low,float high,float value){if(high<=low)return value>=high?1:0;return dySmooth(low,high,value);} +inline float dyMaskRangeWeight(float value,DYREF DYMaskRange& range){ + float low=value>=range.low?1:dyMaskSoftStep(range.low-range.softLow,range.low,value); + float high=value<=range.high?1:1-dyMaskSoftStep(range.high,range.high+range.softHigh,value); + return low*high; +} +inline float dyMaskLeveledCoverage(float raw,DYREF 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 dyMaskFinalCoverage(float a,DYREF DYMaskParameters& p){ + if(p.flags&DYMaskInvert)a=1-a; + return dyClamp(a*p.strength,0,1); +} +inline float dyMaskLevels(float raw,DYREF DYMaskParameters& p){return dyMaskFinalCoverage(dyMaskLeveledCoverage(raw,p),p);} +inline float dyMaskHSLWeight(float3 source,DYREF 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-dyMaskSoftStep(p.hueCoreHalfWidth,outer,distance); + float chroma=(hi-lo)/scale;weight*=hue*dyMaskSoftStep(p.neutralChromaLow,p.neutralChromaHigh,chroma); + } + if(p.flags&DYMaskSaturationEnabled)weight*=dyMaskRangeWeight(hsl.y,p.saturationRange); + if(p.flags&DYMaskLightnessEnabled)weight*=dyMaskRangeWeight(hsl.z,p.lightnessRange); + return weight; +} +inline float dyMaskShapeWeight(float x,float y,DYREF DYMaskParameters& p,DYREF 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 dyMaskSoftStep(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-dyMaskSoftStep(1,1+p.feather,r);return 1-dyMaskSoftStep(1-p.feather,1,r);} + float shorter=physicalWidth=0&&b>=0?1:0;return dyMaskSoftStep(-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=dyMaskRawCoverage(x,y,source,p,path); + return dyMaskLevels(raw,p); +} +#ifndef __METAL_VERSION__ +inline DYMaskParameters dyDefaultMaskParameters(){DYMaskParameters p{};p.version=1;p.centerX=p.centerY=.5f;p.width=p.height=p.gradientWidth=.3f;p.imageAspect=p.strength=1;p.feather=.25f;p.hueCoreHalfWidth=1.f/12;p.hueSoftWidth=1.f/24;p.neutralChromaLow=.002f;p.neutralChromaHigh=.02f;p.saturationRange={0,1,0,0};p.lightnessRange={0,1,0,0};p.inputWhite=p.inputGamma=p.outputWhite=1;return p;} +inline bool dyValidMaskParameters(const DYMaskParameters& p){ + if((p.version!=1&&p.version!=2)||p.kind>DYMaskLumaKey||p.sourceStage>DYMaskSourceLayerInput||(p.flags&~(p.version==1?15u:31u)))return false; + if((p.flags&DYMaskFeatherOutsideFlag)&&p.kind!=DYMaskEllipse&&p.kind!=DYMaskRectangle)return false; + const float *values=&p.centerX;for(size_t i=0;i<(sizeof(p)-offsetof(DYMaskParameters,centerX))/sizeof(float);i++)if(!std::isfinite(values[i]))return false; + if(fabs(p.centerX)>1000||fabs(p.centerY)>1000||p.width<=0||p.height<=0||p.width>4000||p.height>4000||fabs(p.angle)>1000032||p.feather<0||p.feather>1||p.strength<0||p.strength>1||p.gradientWidth<0||p.gradientWidth>4000||p.imageAspect<=0||p.imageAspect>10000)return false; + if(p.hueCenterTurns<0||p.hueCenterTurns>1||p.hueCoreHalfWidth<0||p.hueCoreHalfWidth>.5f||p.hueSoftWidth<0||p.hueSoftWidth>.5f||p.neutralChromaLow<0||p.neutralChromaHigh>1||p.neutralChromaHigh<=p.neutralChromaLow)return false; + for(auto range:{p.saturationRange,p.lightnessRange})if(range.low<0||range.high>1||range.low>range.high||range.softLow<0||range.softHigh<0||range.softLow>1||range.softHigh>1)return false; + return p.inputBlack>=-65504&&p.inputWhite<=65504&&p.inputWhite-p.inputBlack>=.000001f&&p.inputGamma>=.01f&&p.inputGamma<=100&&p.outputBlack>=0&&p.outputWhite<=1&&p.outputBlack<=p.outputWhite; +} +static_assert(sizeof(DYMaskRange)==16,"mask range shared ABI"); +static_assert(sizeof(DYMaskParameters)==128,"mask descriptor shared ABI"); +#endif diff --git a/大鱼调色/Plugin/MaskCore/DYTracker.hpp b/大鱼调色/Plugin/MaskCore/DYTracker.hpp new file mode 100644 index 0000000..9a2bb93 --- /dev/null +++ b/大鱼调色/Plugin/MaskCore/DYTracker.hpp @@ -0,0 +1,364 @@ +#pragma once + +// Independent local motion tracker. Coordinates use an image origin at the top left. +// No target application's code or runtime libraries are used here. +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dy { + +struct GrayFrame { + int width = 0, height = 0; + std::vector pixels; + bool valid() const { + return width >= 16 && height >= 16 && + pixels.size() == static_cast(width) * height; + } + static GrayFrame fromRGBA8(const uint8_t* data, int w, int h, size_t stride) { + if (!data || w <= 0 || h <= 0 || stride < static_cast(w) * 4) return {}; + GrayFrame f{w, h, std::vector(static_cast(w) * h)}; + for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) { + const auto* p = data + y * stride + x * 4; + f.pixels[y * w + x] = (0.2126f * p[0] + 0.7152f * p[1] + 0.0722f * p[2]) / 255.f; + } + return f; + } + static GrayFrame fromBGRA8(const uint8_t* data, int w, int h, size_t stride) { + if (!data || w <= 0 || h <= 0 || stride < static_cast(w) * 4) return {}; + GrayFrame f{w, h, std::vector(static_cast(w) * h)}; + for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) { + const auto* p = data + y * stride + x * 4; + f.pixels[y * w + x] = (0.2126f * p[2] + 0.7152f * p[1] + 0.0722f * p[0]) / 255.f; + } + return f; + } +}; + +struct TrackerROI { + float cx = .5f, cy = .5f, width = .25f, height = .25f, angle = 0; +}; + +struct TrackResult { + float cx = .5f, cy = .5f; + float scale = 1.f, rotation = 0.f; + float confidence = 0.f; + int inliers = 0, features = 0; + bool valid = false; + // Analysis-only additions; the legacy on-disk DYTrackKey stays unchanged. + float scaleX = 1.f, scaleY = 1.f; +}; + +struct FlowPoint { float x,y; }; +struct FlowMatch { FlowPoint p,q; float error; }; +class FlowBackend { +public: + virtual ~FlowBackend() = default; + virtual bool reset(const GrayFrame&) = 0; + virtual bool advance(const GrayFrame&,const std::vector&,std::vector&) = 0; +}; +class Tracker { + using P = FlowPoint; + using Match = FlowMatch; + std::shared_ptr backend_; + std::vector

mask_; + + struct Affine { + double a = 1, b = 0, c = 0, d = 1, tx = 0, ty = 0; + P map(P p) const { + return {static_cast(a*p.x+b*p.y+tx), static_cast(c*p.x+d*p.y+ty)}; + } + double determinant() const {return a*d-b*c;} + static Affine compose(const Affine& m,const Affine& n) { + return {m.a*n.a+m.b*n.c,m.a*n.b+m.b*n.d,m.c*n.a+m.d*n.c,m.c*n.b+m.d*n.d, + m.a*n.tx+m.b*n.ty+m.tx,m.c*n.tx+m.d*n.ty+m.ty}; + } + bool saneStep() const { + double det=determinant(),trace=a*a+b*b+c*c+d*d; + double delta=std::sqrt(std::max(0.,trace*trace-4*det*det)); + double lo=std::sqrt(std::max(0.,(trace-delta)*.5)),hi=std::sqrt(std::max(0.,(trace+delta)*.5)); + return std::isfinite(trace)&&std::isfinite(tx)&&std::isfinite(ty)&&det>0&&lo>.85&&hi<1.18&&std::abs(std::atan2(c-b,a+d))<.15; + } + }; + using Pyramid = std::vector; + Pyramid previous_; + std::vector

points_; + TrackerROI initialROI_; + TrackResult result_; + Affine cumulative_; + P center_{}; + int width_ = 0, height_ = 0, frameIndex_ = 0; + bool active_ = false; + + static float distance(P a, P b) { return std::hypot(a.x-b.x, a.y-b.y); } + static float sample(const GrayFrame& f, float x, float y) { + int ix = static_cast(x), iy = static_cast(y); + float dx = x-ix, dy = y-iy; + const auto* p = f.pixels.data() + iy*f.width+ix; + return (1-dy)*((1-dx)*p[0]+dx*p[1]) + dy*((1-dx)*p[f.width]+dx*p[f.width+1]); + } + static bool inside(const GrayFrame& f, P p, int border) { + return p.x >= border && p.y >= border && p.x < f.width-border-1 && p.y < f.height-border-1; + } + static Pyramid makePyramid(const GrayFrame& f) { + Pyramid p{f}; + while (p.size() < 5 && p.back().width >= 80 && p.back().height >= 80) { + const auto& src = p.back(); + GrayFrame dst{src.width/2, src.height/2, {}}; + dst.pixels.resize(static_cast(dst.width)*dst.height); + for (int y=0; y(std::min(prev.size(),next.size()))-1; + for (;level>0;--level) { + float s=static_cast(1<(1<(1<=0;--level) { + float s=static_cast(1<((hyy*bx-hxy*by)/det); + float dy=static_cast((hxx*by-hxy*bx)/det); + if (!std::isfinite(dx) || !std::isfinite(dy) || std::hypot(dx,dy)>8.f) return false; + q.x+=dx;q.y+=dy;lastError=std::sqrt(sse/count); + if (dx*dx+dy*dy<.0001f) break; + } + if (level>0) {q.x*=2;q.y*=2;} + } + rmse=lastError; + return inside(next[0],q,radius+2) && rmse<.12f; + } + + std::vector

detect(const GrayFrame& frame, const std::vector

& existing) const { + struct Candidate {P p;float score;}; + std::vector candidates; + float halfW=initialROI_.width*width_*.5f; + float halfH=initialROI_.height*height_*.5f; + float c=std::cos(initialROI_.angle),s=std::sin(initialROI_.angle); + double det=cumulative_.determinant(); + float bound=0; + for(float x:{-halfW,halfW})for(float y:{-halfH,halfH}){ + auto p=cumulative_.map({initialROI_.cx*width_+c*x-s*y,initialROI_.cy*height_+s*x+c*y}); + bound=std::max(bound,distance(p,center_)); + } + int minX=std::max(8,static_cast(center_.x-bound)); + int maxX=std::min(width_-9,static_cast(center_.x+bound)); + int minY=std::max(8,static_cast(center_.y-bound)); + int maxY=std::min(height_-9,static_cast(center_.y+bound)); + float best=0; + for (int y=minY;y.5f || std::abs(v)>.5f) continue; + if(mask_.size()>=3) { + bool inside=false; + for(size_t i=0,j=mask_.size()-1;iv)!=(b.y>v))if(u<(b.x-a.x)*(v-a.y)/(b.y-a.y)+a.x)inside=!inside; + } + if(!inside)continue; + } + double xx=0,xy=0,yy=0; + for (int j=-2;j<=2;++j) for (int i=-2;i<=2;++i) { + int idx=(y+j)*width_+x+i; + float gx=(frame.pixels[idx+1]-frame.pixels[idx-1])*.5f; + float gy=(frame.pixels[idx+width_]-frame.pixels[idx-width_])*.5f; + xx+=gx*gx;xy+=gx*gy;yy+=gy*gy; + } + float score=static_cast((xx+yy-std::sqrt((xx-yy)*(xx-yy)+4*xy*xy))*.5); + best=std::max(best,score); + if (score>.0003f) candidates.push_back({{static_cast(x),static_cast(y)},score}); + } + std::sort(candidates.begin(),candidates.end(),[](const auto& a,const auto& b){return a.score>b.score;}); + std::vector

selected=existing; + float minSpacing=std::max(6.f,std::min(width_,height_)*.014f); + for (const auto& candidate:candidates) { + if (candidate.score < best*.012f || selected.size()>=180) break; + bool near=false; + for (const auto& p:selected) if (distance(p,candidate.p)& matches,const std::vector& inliers) { + double px=0,py=0,qx=0,qy=0; + for (int i:inliers) {px+=matches[i].p.x;py+=matches[i].p.y;qx+=matches[i].q.x;qy+=matches[i].q.y;} + double n=static_cast(inliers.size()); + px/=n;py/=n;qx/=n;qy/=n; + double xx=0,xy=0,yy=0,ux=0,uy=0,vx=0,vy=0; + for (int i:inliers) { + double x=matches[i].p.x-px,y=matches[i].p.y-py; + double u=matches[i].q.x-qx,v=matches[i].q.y-qy; + xx+=x*x;xy+=x*y;yy+=y*y;ux+=u*x;uy+=u*y;vx+=v*x;vy+=v*y; + } + double det=xx*yy-xy*xy,trace=xx+yy; + if (!std::isfinite(det)||det<1e-5||det& matches,Affine& model,std::vector& inliers,float& medianError) { + if (matches.size()<8) return false; + std::vector best; + double bestError=std::numeric_limits::max(); + // Three non-collinear correspondences constrain all six affine parameters. + uint32_t random=0x6c8e9cf5u; + auto rng=[&](){random=random*1664525u+1013904223u;return random;}; + for (int attempt=0;attempt<400;++attempt) { + int i=int(rng()%matches.size()),j=int(rng()%matches.size()),k=int(rng()%matches.size()); + if (i==j||i==k||j==k) continue; + auto candidate=fitModel(matches,{i,j,k}); + if (!candidate.saneStep()) continue; + std::vector ids;double e=0; + for (size_t k=0;k(k));e+=d*d;} + } + if (ids.size()>best.size() || (ids.size()==best.size() && e(i)); + if (inliers.size()<8) return false; + best=inliers; + } + std::vector errors; + for (int i:inliers) errors.push_back(distance(model.map(matches[i].p),matches[i].q)); + std::nth_element(errors.begin(),errors.begin()+errors.size()/2,errors.end()); + medianError=errors[errors.size()/2]; + // Reject line-like feature distributions that cannot constrain scale/rotation reliably. + double cx=0,cy=0; + for (int i:inliers) {cx+=matches[i].p.x;cy+=matches[i].p.y;} + cx/=inliers.size();cy/=inliers.size(); + double xx=0,xy=0,yy=0; + for (int i:inliers) {double x=matches[i].p.x-cx,y=matches[i].p.y-cy;xx+=x*x;xy+=x*y;yy+=y*y;} + double trace=xx+yy,small=(trace-std::sqrt((xx-yy)*(xx-yy)+4*xy*xy))*.5; + return model.saneStep()&&inliers.size()>=matches.size()*.52&&small>inliers.size()*8 && small>trace*.005; + } + +public: + void setBackend(std::shared_ptr b) {backend_=std::move(b);active_=false;} + void setMask(std::vector

p) {mask_=std::move(p);} + bool reset(const GrayFrame& frame,TrackerROI roi) { + active_=false;points_.clear();previous_.clear();cumulative_={};frameIndex_=0; + result_={roi.cx,roi.cy,1,0,0,0,0,false}; + if (!frame.valid() || !std::isfinite(roi.cx) || !std::isfinite(roi.cy) || + !std::isfinite(roi.width) || !std::isfinite(roi.height) || !std::isfinite(roi.angle) || + roi.width<=0 || roi.height<=0 || roi.width>8 || roi.height>8 || roi.cx<0 || roi.cx>1 || roi.cy<0 || roi.cy>1) return false; + width_=frame.width;height_=frame.height;initialROI_=roi; + center_={roi.cx*width_,roi.cy*height_}; + points_=detect(frame,{}); + result_.features=static_cast(points_.size());result_.inliers=result_.features; + if (points_.size()<12) return false; + if(backend_){if(!backend_->reset(frame))return false;}else previous_=makePyramid(frame);active_=true;result_.valid=true;result_.confidence=1; + return true; + } + TrackResult track(const GrayFrame& frame) { + if (!active_ || !frame.valid() || frame.width!=width_ || frame.height!=height_) { + result_.valid=false;result_.confidence=0;active_=false;return result_; + } + Pyramid next;if(!backend_)next=makePyramid(frame); + std::vector matches;matches.reserve(points_.size()); + if(backend_) { + if(!backend_->advance(frame,points_,matches)){active_=false;result_.valid=false;result_.confidence=0;return result_;} + } else for (P p:points_) { + P q,back;float error=0,backError=0; + if (!flow(previous_,next,p,p,q,error)) continue; + if (!flow(next,previous_,q,p,back,backError) || distance(back,p)>1.1f) continue; + matches.push_back({p,q,error}); + } + Affine model;std::vector inliers;float medianError=0; + result_.features=static_cast(points_.size()); + result_.inliers=0; + if (!estimate(matches,model,inliers,medianError)) { + active_=false;result_.valid=false;result_.confidence=0;return result_; + } + double stepScale=std::sqrt(model.determinant()); + double stepRotation=std::atan2(model.c-model.b,model.a+model.d); + P nextCenter=model.map(center_); + float retained=static_cast(inliers.size())/points_.size(); + float confidence=std::clamp(retained*std::exp(-medianError*.8f),0.f,1.f); + if (stepScale<.9 || stepScale>1.12 || std::abs(stepRotation)>.12 || confidence<.3f || + !inside(frame,nextCenter,3) || result_.scale*stepScale<.1 || result_.scale*stepScale>10) { + active_=false;result_.valid=false;result_.confidence=confidence;return result_; + } + auto nextCumulative=Affine::compose(model,cumulative_); + // QR decomposition in the initial shape's axes. Output matches the + // persisted position/rotation/two-axis-size model; shear is not authored. + double cs=std::cos(initialROI_.angle),sn=std::sin(initialROI_.angle); + double ax=nextCumulative.a*cs+nextCumulative.b*sn,ay=nextCumulative.c*cs+nextCumulative.d*sn; + double sx=std::hypot(ax,ay),sy=nextCumulative.determinant()/sx; + if(!std::isfinite(sx)||!std::isfinite(sy)||sx<.1||sx>10||sy<.1||sy>10){active_=false;result_.valid=false;result_.confidence=0;return result_;} + cumulative_=nextCumulative; + center_=nextCenter; + result_.cx=center_.x/width_;result_.cy=center_.y/height_; + result_.scale=static_cast(std::sqrt(cumulative_.determinant())); + result_.scaleX=float(sx);result_.scaleY=float(sy); + double relative=std::atan2(ay,ax)-initialROI_.angle; + result_.rotation+=float(std::remainder(relative-result_.rotation,6.2831853071795864769)); + result_.confidence=confidence;result_.inliers=static_cast(inliers.size());result_.valid=true; + points_.clear(); + for (int i:inliers) points_.push_back(matches[i].q); + if (++frameIndex_%5==0 || points_.size()<60) points_=detect(frame,points_); + previous_=std::move(next); + return result_; + } + TrackResult result() const {return result_;} + bool active() const {return active_;} + void stop() {active_=false;result_.valid=false;} +}; + +} // namespace dy