WIP: implement module artwork, adaptive inspector, ordered CMS and local mosaic; host validation pending

这个提交包含在:
mac 于 2026-11-06 13:01:58 +08:00 提交
1 父节点 3452f2344f
当前提交 4b73db8a17
57 个文件已更改
+631 -38

没有与搜索条件相匹配的文件

@@ -56,6 +56,11 @@ if(faceFixture.length){
NSMutableDictionary *masked=DYMutablePlist([[[DYToolDocument alloc]init]autorelease].document);NSMutableDictionary *zero=DYMutablePlist(DYNewMask(DYMaskRectangle));DYMaskParameters zeroP=DYMaskAtTime(zero,kCMTimeZero);zeroP.strength=0;zero[@"parameters"]=[NSData dataWithBytes:&zeroP length:sizeof(zeroP)];masked[@"baseMasks"][@"skin"]=[NSMutableArray arrayWithObject:zero];u.skinVisualize=1;NSError *maskError=nil;BOOL maskOK=[face renderSource:src destination:dst uniforms:u paths:@{}spider:nil tools:masked error:&maskError];Pixels empty=read(dst,gpu);double emptyMax=0;for(NSUInteger i=0;i<w*h;i++)emptyMax=MAX(emptyMax,(float)empty[i*4]);run.record(@"face-preview-respects-authored-zero-strength-mask",maskOK&&emptyMax<.001);
u.skinVisualize=0;u.skinProtection.x=0;NSMutableDictionary *layers=DYMutablePlist([[[DYToolDocument alloc]init]autorelease].document);NSMutableDictionary *skin=(id)DYInsertTool(layers,@"skin",@"base:skin");skin[@"values"][@"skinStrength"]=@100;skin[@"values"][@"skinVisualize"]=@1;BOOL layerOK=[face renderSource:src destination:dst uniforms:u paths:@{}spider:nil tools:layers error:&maskError];Pixels layerMask=read(dst,gpu);double layerFace=0,layerBackground=0;for(NSUInteger y=65;y<185;y++)for(NSUInteger x=175;x<275;x++)layerFace=MAX(layerFace,(float)layerMask[(y*w+x)*4]);for(NSUInteger y=410;y<470;y++)for(NSUInteger x=410;x<470;x++)layerBackground=MAX(layerBackground,(float)layerMask[(y*w+x)*4]);run.record(@"face-independent-layer-uses-own-preview-and-face-mask",layerOK&&layerFace>.01&&layerBackground<.001);
DYDiagnosticTile *twoSource=[[[DYDiagnosticTile alloc]initWithDevice:gpu width:1024 height:512]autorelease],*twoDest=[[[DYDiagnosticTile alloc]initWithDevice:gpu width:1024 height:512]autorelease];Pixels two(1024*512*4);for(NSUInteger y=0;y<512;y++)for(NSUInteger x=0;x<1024;x++)memcpy(two.data()+(y*1024+x)*4,portrait.data()+(y*512+x%512)*4,8);[[twoSource metalTextureForDevice:gpu]replaceRegion:MTLRegionMake2D(0,0,1024,512)mipmapLevel:0 withBytes:two.data()bytesPerRow:1024*8];u.skinProtection.x=1;BOOL twoOK=[face renderSource:twoSource destination:twoDest uniforms:u paths:@{}error:&maskError];NSData *twoEntries=[face valueForKey:@"faceEntries"];const DYToolMaskEntry *twoMasks=(const DYToolMaskEntry*)twoEntries.bytes;NSInteger faceCount=0;for(NSUInteger i=0;i<twoEntries.length/sizeof(*twoMasks);i++)faceCount+=twoMasks[i].section==-100;run.record(@"face-multiple-people-build-independent-support-regions",twoOK&&faceCount==2,@{@"faces":@(faceCount)});
NSMutableDictionary *privacy=DYMutablePlist(DYInitialToolDocument(nil));privacy[@"mosaic"]=@{@"enabled":@YES,@"source":@"face",@"size":@64};DYUniforms privacyU=defaults;privacyU.primarySectionEnabled=0;privacyU.skinProtection.x=0;
BOOL privacyOK=[face renderSource:src destination:dst uniforms:privacyU paths:@{} spider:nil tools:privacy colorManagement:nil hostPrimaries:kFxColorPrimaries_Rec709 error:&maskError];Pixels privateFrame=read(dst,gpu);
privacy[@"mosaic"] = @{@"enabled":@NO,@"source":@"face",@"size":@64};BOOL privacyOff=[face renderSource:src destination:dst uniforms:privacyU paths:@{} spider:nil tools:privacy colorManagement:nil hostPrimaries:kFxColorPrimaries_Rec709 error:&maskError];Pixels privateReference=read(dst,gpu);
double privateInside=0,privateOutside=0;for(NSUInteger y=85;y<145;y++)for(NSUInteger x=200;x<260;x++)for(int c=0;c<3;c++)privateInside=MAX(privateInside,fabs((float)privateFrame[(y*w+x)*4+c]-(float)privateReference[(y*w+x)*4+c]));for(NSUInteger y=410;y<470;y++)for(NSUInteger x=410;x<470;x++)for(int c=0;c<3;c++)privateOutside=MAX(privateOutside,fabs((float)privateFrame[(y*w+x)*4+c]-(float)privateReference[(y*w+x)*4+c]));
run.record(@"mosaic-real-face-includes-feature-region-and-excludes-background",privacyOK&&privacyOff&&privateInside>.05&&privateOutside==0,@{@"faceChange":@(privateInside),@"backgroundChange":@(privateOutside)});
Pixels noFace(w*h*4);for(NSUInteger i=0;i<w*h;i++){noFace[i*4]=.35;noFace[i*4+1]=.18;noFace[i*4+2]=.1;noFace[i*4+3]=1;}upload(noFace);u.skinVisualize=0;Pixels noFaceProtected=render(run,face,src,dst,gpu,u,@{},@"face-none-protected-render");u.skinProtection.x=0;Pixels noFacePlain=render(run,face,src,dst,gpu,u,@{},@"face-none-unprotected-reference");run.record(@"face-no-detection-clears-prior-frame-and-fails-closed",difference(noFaceProtected,noFacePlain).maximum<.002);
}
@@ -10,11 +10,11 @@
NSDictionary *values=[[host->_values copy]autorelease],*custom=[[host->_custom copy]autorelease];int starts=host->_undoStarts,ends=host->_undoEnds;
[settings performClick:nil];[view layoutSubtreeIfNeeded];run.record(@"compact-color-settings-button-expands-panel",!panel.hidden&&first.frame.origin.y>=NSMaxY(panel.frame)+12&&settings.state==NSControlStateValueOn);
run.record(@"inspector-preferred-height-follows-content-with-a-scroll-cap",foldedHeight<780&&view.intrinsicContentSize.height>foldedHeight&&view.intrinsicContentSize.height<=780);
run.record(@"inspector-preferred-height-follows-complete-content",view.intrinsicContentSize.height>foldedHeight);
double layoutDeadline=NSProcessInfo.processInfo.systemUptime+.02;
while(NSProcessInfo.processInfo.systemUptime<layoutDeadline)[[NSRunLoop mainRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:.002]];
NSView *brandLabel=[view valueForKey:@"brand"];NSScrollView *cardsScroll=[view valueForKey:@"scroll"];
run.record(@"inspector-hosted-slot-keeps-header-visible-and-scrolls-only-overflow",NSEqualRects(view.frame,hostSlot.bounds)&&NSContainsRect(view.bounds,brandLabel.frame)&&cardsScroll.documentView.frame.size.height>cardsScroll.contentSize.height);
run.record(@"inspector-grows-with-content-and-has-no-inner-scroll-view",view.frame.size.height==view.intrinsicContentSize.height&&NSContainsRect(view.bounds,brandLabel.frame)&&cardsScroll==nil);
for(int i=0;i<9;i++){[settings performClick:nil];[view layoutSubtreeIfNeeded];}
run.record(@"compact-color-settings-repeated-toggle-does-not-edit-grade",panel.hidden&&first.frame.origin.y==8&&[values isEqual:host->_values]&&[custom isEqual:host->_custom]&&starts==host->_undoStarts&&ends==host->_undoEnds);
+1
查看文件
@@ -528,6 +528,7 @@ extern "C" int DYRunDiagnostics(void) { @autoreleasepool {
#include "DYMaskPanelDiagnostics.inc.h"
#include "DYManagedDiagnostics.inc.h"
#include "DYPrimaryDiagnostics.inc.h"
#include "DYUnifiedDiagnostics.inc.h"
#include "DYCompactUIDiagnostics.inc.h"
#include "DYViewerParameterDiagnostics.inc.h"
#include "DYViewerControlsDiagnostics.inc.h"
+5
查看文件
@@ -17,6 +17,11 @@
VNImageRequestHandler *handler=[[VNImageRequestHandler alloc]initWithCGImage:cg orientation:kCGImagePropertyOrientationUp options:@{}];CGImageRelease(cg);
if([handler performRequests:@[request] error:nil])for(VNFaceObservation *face in request.results){
if(entries.size()>64||face.confidence<.5||!face.landmarks.faceContour.pointCount)continue;CGRect box=face.boundingBox;if(box.size.width<.015||box.size.height<.015)continue;
// Privacy coverage includes eyes, brows and mouth. Skin's feature holes must
// never punch through the mosaic. A padded rectangle covers the full face.
DYToolMaskEntry privacy{};privacy.section=-102;privacy.mask.parameters=dyDefaultMaskParameters();
privacy.mask.parameters.kind=DYMaskRectangle;privacy.mask.parameters.centerX=CGRectGetMidX(box);privacy.mask.parameters.centerY=1-CGRectGetMidY(box);
privacy.mask.parameters.width=box.size.width*1.2;privacy.mask.parameters.height=box.size.height*1.25;privacy.mask.parameters.feather=0;entries.push_back(privacy);
DYToolMaskEntry support{};support.section=-100;support.mask.parameters=dyDefaultMaskParameters();auto &p=support.mask.parameters;p.kind=DYMaskBezier;p.centerX=CGRectGetMidX(box);p.centerY=1-CGRectGetMidY(box);p.width=box.size.width;p.height=box.size.height;p.feather=.1;
auto &path=support.mask.path;VNFaceLandmarkRegion2D *contour=face.landmarks.faceContour;
for(NSUInteger i=0;i<contour.pointCount;i++){CGPoint q=contour.normalizedPoints[i];path.x[path.count]=q.x-.5;path.y[path.count]=.5-q.y;path.count++;}
+25
查看文件
@@ -396,3 +396,28 @@ kernel void dyCloneStamps(texture2d<float,access::read> input [[texture(0)]],
}
output.write(color,gid);
}
// Block-centre sampling is stable in image coordinates and never feeds back.
kernel void dyLocalMosaic(texture2d<float,access::read> input [[texture(0)]],texture2d<float,access::write> output [[texture(1)]],device const DYToolMaskEntry* masks [[buffer(0)]],constant DYToolMaskHeader& h [[buffer(1)]],constant uint& block [[buffer(2)]],uint2 p [[thread_position_in_grid]]) {
uint2 size=uint2(output.get_width(),output.get_height());if(any(p>=size))return;
float4 original=input.read(p);float2 uv=(float2(p)+.5f)/float2(size);float3 code=dyToolEncode(original.a>0?original.rgb/original.a:float3(0));float coverage=0;
if(h.section==-102){float x=h.offsetX+uv.x*h.scaleX,y=h.offsetY+uv.y*h.scaleY;for(uint i=0;i<h.count;i++)if(masks[i].section==-102)coverage=max(coverage,dyToolMask(x,y,code,masks[i].mask));}
else if(h.count)coverage=dyToolCoverage(uv,code,masks,h,h.section);
if(coverage<=0){output.write(original,p);return;}
uint2 q=min((p/block)*block+block/2,size-1);float4 sample=input.read(q);
// Preserve the pixel's original alpha and prevent transparent samples turning
// into arbitrary RGB on an otherwise opaque face.
float3 rgb=sample.a>0?sample.rgb/sample.a*original.a:original.rgb;
output.write(float4(mix(original.rgb,rgb,coverage),original.a),p);
}
// Extend bounded creative operators by their boundary delta. The float32
// residual carries negative / above-one values around the historical bounded
// kernels. Neutral tools skip this adapter entirely. This is a declared code
// domain extension, not a tone map and not an intermediate output transform.
kernel void dyUnifiedBridgeIn(texture2d<float,access::read> a [[texture(0)]],texture2d<float,access::write> b [[texture(1)]],uint2 p [[thread_position_in_grid]]){
if(any(p>=uint2(b.get_width(),b.get_height())))return;float4 c=a.read(p);if(c.a>0)c.rgb=dyToolDecode(clamp(c.rgb/c.a,0.f,1.f))*c.a;b.write(c,p);
}
kernel void dyUnifiedBridgeOut(texture2d<float,access::read> raw [[texture(0)]],texture2d<float,access::read> changed [[texture(1)]],texture2d<float,access::write> out [[texture(2)]],uint2 p [[thread_position_in_grid]]){
if(any(p>=uint2(out.get_width(),out.get_height())))return;float4 a=raw.read(p),b=changed.read(p);if(a.a>0&&b.a>0){float3 c=a.rgb/a.a;float3 delta=dyToolEncode(b.rgb/b.a)-clamp(c,0.f,1.f);a.rgb=(c+delta)*a.a;}out.write(a,p);
}
+54 -18
查看文件
@@ -211,12 +211,12 @@ static NSArray *DYAccessibleSubviews(NSView *view, BOOL visibleOnly) {
}
@end
static NSArray *DYPresentationSections(BOOL cstOnly) {
static NSArray *DYPresentationSections(BOOL cstOnly,BOOL splitOutput) {
NSMutableDictionary *bySection=[NSMutableDictionary dictionary],*byKey=[NSMutableDictionary dictionary];
for(NSDictionary *s in DYSections())bySection[s[@"key"]]=s;
for(NSDictionary *d in DYDescriptors())byKey[d[@"key"]]=d;
NSMutableDictionary *primary=[[bySection[@"primary"]mutableCopy]autorelease];NSMutableArray *cmRows=[NSMutableArray array];
for(NSString *part in (cstOnly?@[@"input",@"output"]:@[@"input",@"primary",@"output"])){
for(NSString *part in (splitOutput?(cstOnly?@[@"input"]:@[@"input",@"primary"]):(cstOnly?@[@"input",@"output"]:@[@"input",@"primary",@"output"]))){
[cmRows addObject:@{@"key":[@"heading:" stringByAppendingString:part],@"title":[part isEqual:@"input"]?@"输入与工作空间":[part isEqual:@"output"]?@"输出转换":@"一级调色"}];
for(NSDictionary *d in bySection[part][@"rows"]){NSString *key=d[@"key"];if([key hasPrefix:@"cmbypass"]||[key isEqual:@"cmbalanceStrength"])continue;
if([key isEqual:@"cmbalanceAngle"])[cmRows addObject:@{@"key":@"primaryBalance",@"kind":@"balanceWheel",@"title":@"一级白平衡色轮"}];else[cmRows addObject:d];}
@@ -227,7 +227,7 @@ static NSArray *DYPresentationSections(BOOL cstOnly) {
for(NSString *key in @[@"temperature",@"tint",@"exposure",@"contrast",@"highlights",@"shadows",@"whites",@"blacks",@"texture",@"clarity",@"dehaze",@"vibrance",@"saturation",@"skinEnabled",@"copyAutoGrade"]){NSDictionary*d=byKey[key];if(d)[rows addObject:d];}
base[@"rows"]=rows;base[@"extraEnabled"]=bySection[@"color"][@"enabled"];
base[@"title"]=@"基础调整";
return @[primary,bySection[@"spider"],base,bySection[@"skin"],bySection[@"look"],bySection[@"hsl"],bySection[@"curve"],bySection[@"grading"],bySection[@"primaries"],bySection[@"levels"],bySection[@"blackwhite"],bySection[@"balance"],bySection[@"mixer"],bySection[@"film"],bySection[@"lens"]];
NSMutableArray *presentation=[NSMutableArray arrayWithArray:@[primary,bySection[@"spider"],base,bySection[@"skin"],bySection[@"look"],bySection[@"hsl"],bySection[@"curve"],bySection[@"grading"],bySection[@"primaries"],bySection[@"levels"],bySection[@"blackwhite"],bySection[@"balance"],bySection[@"mixer"],bySection[@"film"],bySection[@"lens"]]];if(splitOutput)[presentation addObject:bySection[@"output"]];return presentation;
}
@@ -488,7 +488,7 @@ NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing>
NSInteger _visibleLooks;
NSButton *_colorSettings;BOOL _colorSettingsExpanded;
BOOL _refreshing,_graphicUndoOpen,_graphicCancelled;CMTime _graphicTime;NSMutableDictionary *_graphicExpected;
BOOL _embedded,_workspaceEditor;NSMutableDictionary *_stackViews;NSArray *_stackOrder;NSDictionary *_stackRoots;CGFloat _stackHeight,_preferredHeight;
BOOL _embedded,_workspaceEditor,_unified;NSArray *_renderOrder;NSMutableDictionary *_stackViews;NSArray *_stackOrder;NSDictionary *_stackRoots;CGFloat _stackHeight,_preferredHeight;
DYSpiderPanel *_spiderPanel;
NSMutableDictionary *_assetLoads,*_assetLoadIDs;
NSUInteger _nextAssetLoadID;
@@ -516,7 +516,7 @@ NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing>
_preferredHeight=(_embedded||_workspaceEditor)?780:406;
BOOL cstOnly=NO;
if(!_embedded){id<FxCustomParameterActionAPI_v4>action=[manager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(action){[action startAction:self];@try{cstOnly=[DYReadTools(manager,action.currentTime).document[@"starterTool"]isEqual:@"cst"];}@finally{[action endAction:self];}}}
NSArray *presentation=DYPresentationSections(cstOnly);if(_embedded||_workspaceEditor){NSMutableArray *filtered=[NSMutableArray array];for(NSDictionary *s in presentation)if([s[@"key"]isEqual:_workspaceEditor?workspaceType:[(DYToolManager*)manager type]])[filtered addObject:s];presentation=filtered;}
NSArray *presentation=DYPresentationSections(cstOnly,!_embedded&&!_workspaceEditor);if(_embedded||_workspaceEditor){NSMutableArray *filtered=[NSMutableArray array];for(NSDictionary *s in presentation)if([s[@"key"]isEqual:_workspaceEditor?workspaceType:[(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];
@@ -538,14 +538,14 @@ NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing>
_save.identifier=@"primaryAction";
_workspaceButton=[DYButton(@"控制面板",self,@selector(openWorkspace:))retain];_workspaceButton.accessibilityLabel=@"打开调色控制面板";
_addModule=[[DYThemePopUpButton alloc]initWithFrame:NSZeroRect pullsDown:YES];_addModule.font=[NSFont systemFontOfSize:11];_addModule.accessibilityLabel=@"添加模块";[_addModule addItemWithTitle:@"+ 添加模块"];
for(NSDictionary *section in DYPresentationSections(NO)){NSMenuItem *item=[[[NSMenuItem alloc]initWithTitle:section[@"title"] action:@selector(addModule:) keyEquivalent:@""]autorelease];item.target=self;item.representedObject=section[@"key"];[_addModule.menu addItem:item];}
for(NSDictionary *section in DYPresentationSections(NO,NO)){NSMenuItem *item=[[[NSMenuItem alloc]initWithTitle:section[@"title"] action:@selector(addModule:) keyEquivalent:@""]autorelease];item.target=self;item.representedObject=section[@"key"];[_addModule.menu addItem:item];}
for(NSView *v in @[_brand,_subtitle,_websiteLink,_resetAll,_save,_load,_export,_colorSettings,_addModule,_workspaceButton]){[self addSubview:v];v.hidden=_embedded||_workspaceEditor;}
NSMutableArray *themes=[NSMutableArray array];for(NSInteger i=0;i<DYThemeNames().count;i++){
NSButton *b=DYButton(DYThemeNames()[i],self,@selector(selectTheme:));[b setButtonType:NSButtonTypePushOnPushOff];b.tag=i+7;b.identifier=@"appearanceToggle";
b.toolTip=[DYThemeNames()[i] stringByAppendingString:@"主题"];b.accessibilityLabel=b.toolTip;[self addSubview:b];b.hidden=_embedded||_workspaceEditor;[themes addObject:b];
}_themeButtons=[themes copy];
_scroll=[[DYInspectorScrollView alloc] initWithFrame:NSZeroRect];
_scroll.hasVerticalScroller=!_embedded&&!_workspaceEditor; _scroll.hasHorizontalScroller=_workspaceEditor;_scroll.scrollerStyle=NSScrollerStyleOverlay;_scroll.automaticallyAdjustsContentInsets=NO;_scroll.contentInsets=NSEdgeInsetsZero; _scroll.drawsBackground=NO;
if(_workspaceEditor)_scroll=[[DYInspectorScrollView alloc] initWithFrame:NSZeroRect];
_scroll.hasVerticalScroller=NO; _scroll.hasHorizontalScroller=_workspaceEditor;_scroll.scrollerStyle=NSScrollerStyleOverlay;_scroll.automaticallyAdjustsContentInsets=NO;_scroll.contentInsets=NSEdgeInsetsZero; _scroll.drawsBackground=NO;
_scroll.autohidesScrollers=YES; _scroll.borderType=NSNoBorder;
_scroll.clipsToBounds=YES;_scroll.wantsLayer=YES;_scroll.layer.masksToBounds=YES;
_scroll.contentView.clipsToBounds=YES;
@@ -553,7 +553,8 @@ NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing>
_scroll.accessibilityLabel=@"调色参数滚动区";
_document=[[DYFlippedView alloc] initWithFrame:NSMakeRect(0,0,360,1000)];
_document.accessibilityLabel=@"调色参数";_document.identifier=@"inspectorBackground";
_scroll.documentView=_document; [self addSubview:_scroll];
if(_scroll){_scroll.documentView=_document;[self addSubview:_scroll];}
else [self addSubview:_document];
if(!_embedded&&!_workspaceEditor){_managedPanel=[[DYManagedColorPanel alloc]initWithManager:_manager renderer:_renderer assetTarget:self];_managedPanel.hidden=YES;[_document addSubview:_managedPanel];}
[self buildCards];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(modelChanged:) name:@"DYModelChanged" object:_manager];
@@ -577,7 +578,7 @@ NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing>
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];[NSWorkspace.sharedWorkspace.notificationCenter removeObserver:self];
if(_embedded)[(id)_manager release];[_stackViews release];[_stackOrder release];[_stackRoots release];
if(_embedded)[(id)_manager release];[_stackViews release];[_stackOrder release];[_stackRoots release];[_renderOrder release];
[_brand release]; [_subtitle release]; [_websiteLink release]; [_resetAll release]; [_save release]; [_load release]; [_export release];[_colorSettings release];[_addModule release];
[_managedPanel release];[_scroll release]; [_document release]; [_sections release]; [_cards release]; [_controls release]; [_assetButtons release]; [_graphics release]; [_sampler release];
[_recentBrowser close];[_recentBrowser release];[_recentHost release];
@@ -605,6 +606,19 @@ NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing>
if([NSThread isMainThread]) {[self refresh];NSString *ID=n.userInfo[@"scrollToTool"];if(!_embedded&&ID.length&&_stackViews[ID]){[self layoutSubtreeIfNeeded];NSView *child=_stackViews[ID];[_document scrollPoint:NSMakePoint(0,MAX(0,child.frame.origin.y-8))];}}
else dispatch_async(dispatch_get_main_queue(),^{ [self refresh]; });
}
- (void)moveOutput:(NSButton*)button {
id<FxCustomParameterActionAPI_v4>a=[self actionAPI];[a startAction:self];
@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(_manager,a.currentTime).document);NSMutableArray *visible=[NSMutableArray array];
for(NSString *ID in DYUnifiedRenderOrder(doc)){BOOL shown=[ID isEqual:@"output"]||_stackViews[ID]!=nil;if([ID hasPrefix:@"base:"])for(NSDictionary *card in _cards)if([card[@"section"][@"key"]isEqual:[ID substringFromIndex:5]])shown=![card[@"removed"]boolValue];if(shown)[visible addObject:ID];}
NSInteger index=[visible indexOfObject:@"output"],target=index+button.tag;if(index==NSNotFound||target<0||target>=visible.count)return;
[visible exchangeObjectAtIndex:index withObjectAtIndex:target];
// Input interpretation remains at the front. Output may follow the first
// grading node, but it cannot precede the declared input conversion.
if(target==0)return;
doc[@"outputAfter"]=target==visible.count-1?@"tail":visible[target-1];
id<FxUndoAPI>undo=[_manager apiForProtocol:@protocol(FxUndoAPI)];if([undo startUndoGroup:@"移动输出转换层"]){DYWriteTools(_manager,doc,a.currentTime);[undo endUndoGroup];}
}@finally{[a endAction:self];}[self postChanged];
}
- (void)selectTheme:(NSButton *)button {DYSetThemeIndex(button.tag);}
- (void)toggleColorSettings:(id)sender {
_colorSettingsExpanded=!_colorSettingsExpanded;_managedPanel.hidden=!_colorSettingsExpanded;_colorSettings.state=_colorSettingsExpanded?NSControlStateValueOn:NSControlStateValueOff;
@@ -824,7 +838,7 @@ NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing>
NSArray *actions=@[_save,_load,_export,_colorSettings];for(NSUInteger i=0;i<actions.count;i++)[actions[i]setFrame:NSMakeRect(16+(bw+gap)*(compact?i%2:i),74+(compact?i/2*34:0),bw,27)];
CGFloat top=(compact?178:144)+34;_workspaceButton.frame=NSMakeRect(16,top-70,w-32,27);_addModule.frame=NSMakeRect(16,top-36,w-32,27);
_scroll.frame=(_embedded||_workspaceEditor)?NSMakeRect(0,0,w,h):NSMakeRect(0,top,w,MAX(0,h-top));
CGFloat cw=MAX(244,_scroll.contentSize.width-32),y=8;
CGFloat cw=MAX(244,(_scroll?_scroll.contentSize.width:w)-32),y=8;
if(_managedPanel&&!_managedPanel.hidden){_managedPanel.frame=NSMakeRect(28,y,cw-24,_managedPanel.contentHeight);y+=_managedPanel.contentHeight+12;}
for(NSMutableDictionary *c in _cards) {
DYCard *card=c[@"view"];BOOL collapsed=[c[@"collapsed"]boolValue];NSString *key=c[@"section"][@"key"];
@@ -905,18 +919,32 @@ NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing>
[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)];
}
y=[self layoutRepeatedToolsAfter:@"tail" y:y width:w];
_stackHeight=y;CGFloat documentWidth=_scroll.contentSize.width;if(_workspaceEditor)for(NSDictionary *card in _cards)documentWidth=MAX(documentWidth,[card[@"view"]frame].size.width);[_document setFrameSize:NSMakeSize(documentWidth,_workspaceEditor?_scroll.contentSize.height:MAX(y,_scroll.contentSize.height))];
if(_unified&&!_embedded&&!_workspaceEditor){
NSMutableDictionary *views=[NSMutableDictionary dictionary];
for(NSDictionary *card in _cards){NSString *key=card[@"section"][@"key"];NSView *view=card[@"view"];if(!view.hidden)views[[key isEqual:@"output"]?@"output":[@"base:" stringByAppendingString:key]]=view;}
[views addEntriesFromDictionary:_stackViews];y=(_managedPanel&&!_managedPanel.hidden)?NSMaxY(_managedPanel.frame)+12:8;
for(NSString *ID in _renderOrder){NSView *view=views[ID];if(!view||view.hidden)continue;NSRect frame=view.frame;frame.origin.y=y;view.frame=frame;y+=frame.size.height+([ID hasPrefix:@"base:"]||[ID isEqual:@"output"]?12:0);}
}
for(NSDictionary *card in _cards)if([card[@"section"][@"key"]isEqual:@"output"]){
[card[@"maskButton"]setHidden:YES];[card[@"maskBadge"]setHidden:YES];
NSButton *up=card[@"repeatButton"],*down=card[@"removeButton"];up.image=down.image=nil;up.title=@"↑";down.title=@"↓";up.tag=-1;down.tag=1;up.action=down.action=@selector(moveOutput:);up.toolTip=@"输出转换上移一层";down.toolTip=@"输出转换下移一层";up.accessibilityLabel=up.toolTip;down.accessibilityLabel=down.toolTip;
}
_stackHeight=y;CGFloat documentWidth=_scroll?_scroll.contentSize.width:w;if(_workspaceEditor)for(NSDictionary *card in _cards)documentWidth=MAX(documentWidth,[card[@"view"]frame].size.width);
_document.frame=NSMakeRect(0,(_embedded||_workspaceEditor)?0:top,documentWidth,_workspaceEditor?_scroll.contentSize.height:y);
if(!_embedded&&!_workspaceEditor){
CGFloat preferred=MIN(780,ceil(top+MAX(12,y)));
CGFloat preferred=ceil(top+MAX(12,y));
if(preferred!=_preferredHeight){
_preferredHeight=preferred;
// FCP owns the attached custom parameter's slot. Resizing the
// remote child there bottom-aligns it and clips the fixed header.
// Notify ViewBridge after the parameter action has unwound. The
// entire document has one natural height; only the host scrolls.
dispatch_async(dispatch_get_main_queue(),^{
if(preferred!=self->_preferredHeight)return;
[self invalidateIntrinsicContentSize];
if(!self.superview&&!self.window&&self.frame.size.height!=preferred)
if(self.frame.size.height!=preferred)
[self setFrameSize:NSMakeSize(self.frame.size.width,preferred)];
[self.superview setNeedsLayout:YES];
NSAccessibilityPostNotification(self,NSAccessibilityLayoutChangedNotification);
});
}
}
@@ -933,6 +961,14 @@ NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing>
@try {
CMTime t=action.currentTime;
id<FxParameterRetrievalAPI_v6> get=[_manager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];
if(!_embedded&&!_workspaceEditor){
_unified=DYUnifiedColorState(DYReadAssets(_manager,t).colorManagement);
[_renderOrder release];_renderOrder=[DYUnifiedRenderOrder(DYReadTools(_manager,t).document)copy];
NSMutableDictionary *primary=nil,*output=nil;for(NSMutableDictionary *card in _cards){if([card[@"section"][@"key"]isEqual:@"primary"])primary=card;if([card[@"section"][@"key"]isEqual:@"output"])output=card;}
NSMutableArray *body=[NSMutableArray arrayWithArray:primary[@"body"]];
for(NSView *row in output[@"body"]){if([row.identifier isEqual:@"toolMasks"])continue;[body removeObjectIdenticalTo:row];[(_unified?output:primary)[@"view"]addSubview:row];if(!_unified)[body addObject:row];}
primary[@"body"]=body;
}
NSMutableDictionary *graphicValues=[NSMutableDictionary dictionary];
for(NSNumber *pid in _controls) {
NSDictionary *r=_controls[pid],*d=r[@"descriptor"]; double v=[d[@"default"] doubleValue];
@@ -968,7 +1004,7 @@ NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing>
if(!_embedded){DYInspectorToken *token=nil;[get getCustomParameterValue:&token fromParameter:DYInspectorParameterID atTime:t];visible=[tools[@"starterTool"]isEqual:type]||[@[@"primary",@"base",@"spider",@"hsl"]containsObject:type]||[token.folds[[@"visible:" stringByAppendingString:type]]boolValue];
if(!visible){for(NSDictionary*d in DYBaseToolDescriptors(type)){double value=[d[@"default"]doubleValue];[get getFloatValue:&value fromParameter:[d[@"pid"]unsignedIntValue]atTime:t];if(std::isfinite(value)&&fabs(value-[d[@"default"]doubleValue])>1e-6){visible=YES;break;}}if([tools[@"baseMasks"][type]count])visible=YES;if([type isEqual:@"look"])for(NSString *assetKey in DYReadAssets(_manager,t).paths)if([assetKey hasPrefix:@"look"])visible=YES;}
}
BOOL removed=!_embedded&&(DYBaseToolRemoved(tools,type)||(!_workspaceEditor&&!visible));groupingChanged|=[card[@"removed"]boolValue]!=removed;((NSMutableDictionary *)card)[@"removed"]=@(removed);
BOOL removed=[type isEqual:@"output"]?!_unified:!_embedded&&(DYBaseToolRemoved(tools,type)||(!_workspaceEditor&&!visible));groupingChanged|=[card[@"removed"]boolValue]!=removed;((NSMutableDictionary *)card)[@"removed"]=@(removed);
[card[@"maskPanel"]refreshWithDocument:tools time:t];
NSString *nodeID=_embedded?[(DYToolManager*)_manager nodeID]:[@"base:" stringByAppendingString:card[@"section"][@"key"]];NSUInteger count=[DYMasksForTool(tools,nodeID) count];
[(DYMaskCountBadge*)card[@"maskBadge"]setCount:count];NSString *hint=count?[NSString stringWithFormat:@"已有 %lu 个蒙版;点击添加独立蒙版",(unsigned long)count]:@"添加本工具的独立蒙版";
@@ -1075,7 +1111,7 @@ NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing>
id<FxParameterSettingAPI_v6> set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];
[set setFloatValue:enabled?1:0 toParameter:pid.unsignedIntValue atTime:action.currentTime];
NSNumber *extra=section[@"extraEnabled"];if(extra)[set setFloatValue:enabled?1:0 toParameter:extra.unsignedIntValue atTime:action.currentTime];
for(NSNumber *linked in section[@"enableParameters"])[set setFloatValue:enabled?1:0 toParameter:linked.unsignedIntValue atTime:action.currentTime];
if(!(_unified&&[section[@"key"]isEqual:@"primary"]))for(NSNumber *linked in section[@"enableParameters"])[set setFloatValue:enabled?1:0 toParameter:linked.unsignedIntValue atTime:action.currentTime];
}
@finally {[action endAction:self];}
+2
查看文件
@@ -4,6 +4,8 @@
// Separate authoring state; absent state always selects the unchanged v1 renderer.
FOUNDATION_EXPORT NSDictionary *DYManagedColorDefaults(void);
FOUNDATION_EXPORT NSDictionary *DYPrimaryColorDefaults(void);
FOUNDATION_EXPORT NSDictionary *DYUnifiedColorDefaults(void);
FOUNDATION_EXPORT BOOL DYUnifiedColorState(NSDictionary *state);
FOUNDATION_EXPORT BOOL DYPrimaryColorState(NSDictionary *state);
FOUNDATION_EXPORT void DYSeedPrimaryWorkingSpace(NSMutableDictionary *node,float transfer,float gamut);
FOUNDATION_EXPORT BOOL DYManagedColorValid(id state,NSError **error);
+4 -1
查看文件
@@ -5,7 +5,9 @@
#include <cmath>
NSDictionary *DYManagedColorDefaults(void){return @{@"version":@2,@"mode":@1,@"input":@109,@"output":@1,@"gamutCompression":@YES,@"engine":@"OpenColorIO-2.5.2",@"config":@"studio-config-v2.2.0_aces-v1.3_ocio-v2.4"};}
NSDictionary *DYPrimaryColorDefaults(void){return @{@"version":@3,@"mode":@4,@"engine":@"Dayu-CST-f32",@"config":@"primary-parameters-v1"};}
BOOL DYPrimaryColorState(NSDictionary *s){return [s isKindOfClass:NSDictionary.class]&&[s[@"version"]isEqual:@3]&&[s[@"mode"]isEqual:@4];}
NSDictionary *DYUnifiedColorDefaults(void){return @{@"version":@4,@"mode":@5,@"engine":@"Dayu-CST-f32",@"config":@"ordered-working-domain-v1"};}
BOOL DYUnifiedColorState(NSDictionary *s){return [s isKindOfClass:NSDictionary.class]&&[s[@"version"]isEqual:@4]&&[s[@"mode"]isEqual:@5];}
BOOL DYPrimaryColorState(NSDictionary *s){return DYUnifiedColorState(s)||([s isKindOfClass:NSDictionary.class]&&[s[@"version"]isEqual:@3]&&[s[@"mode"]isEqual:@4]);}
void DYSeedPrimaryWorkingSpace(NSMutableDictionary *node,float transfer,float gamut){
if(![node[@"type"]isEqual:@"primary"])return;NSMutableDictionary*v=node[@"values"];NSUInteger follow=[node[@"primaryFollow"]unsignedIntegerValue],bit=1;
for(NSString *part in @[@"input",@"working",@"output"]){NSString*t=[NSString stringWithFormat:@"cm%@Transfer",part],*g=[NSString stringWithFormat:@"cm%@Gamut",part];if(!v[t]&&!v[g])follow|=bit;if(!v[t])v[t]=@(transfer);if(!v[g])v[g]=@(gamut);bit<<=1;}node[@"primaryFollow"]=@(follow);
@@ -19,6 +21,7 @@ void DYPrimaryControlChanged(id<PROAPIAccessing> manager,CMTime time,NSString *k
NSArray<NSDictionary*> *DYManagedInputSpaces(void){NSMutableArray *a=[NSMutableArray array];for(const auto&s:dycm::spaces())[a addObject:@{@"id":@(unsigned(s.id)),@"name":@(s.label)}];return a;}
NSArray<NSDictionary*> *DYManagedOutputSpaces(void){NSMutableArray *a=[NSMutableArray array];for(const auto&s:dycm::outputs())[a addObject:@{@"id":@(unsigned(s.id)),@"name":@(s.label)}];return a;}
BOOL DYManagedColorValid(id state,NSError **error){
if(DYUnifiedColorState(state))return [state isEqual:DYUnifiedColorDefaults()];
if(DYPrimaryColorState(state)){BOOL valid=[state isEqual:DYPrimaryColorDefaults()];if(!valid&&error)*error=[NSError errorWithDomain:@"com.dayu.color.cms" code:1 userInfo:@{NSLocalizedDescriptionKey:@"一级 CST 设置版本不匹配。"}];return valid;}
BOOL valid=[state isKindOfClass:NSDictionary.class]&&[state count]==7&&[state[@"version"]isEqual:@2]&&[state[@"engine"]isEqual:@"OpenColorIO-2.5.2"]&&[state[@"config"]isEqual:@"studio-config-v2.2.0_aces-v1.3_ocio-v2.4"];
for(NSString *key in @[@"mode",@"input",@"output",@"gamutCompression"]){id v=[state isKindOfClass:NSDictionary.class]?state[key]:nil;double n=[v isKindOfClass:NSNumber.class]?[v doubleValue]:NAN;valid&=std::isfinite(n)&&n==floor(n);}
+6 -6
查看文件
@@ -13,11 +13,11 @@
NSDictionary *_state;NSString *_inputLUTPath;NSUInteger _selectionGeneration;BOOL _refreshing;
}
- (BOOL)isFlipped{return YES;}
- (CGFloat)contentHeight{NSInteger m=[_state[@"mode"]integerValue];return m==0?82:(m==1||m==4)?110:238;}
- (CGFloat)contentHeight{NSInteger m=[_state[@"mode"]integerValue];return m==0?82:(m==1||m>=4)?110:238;}
static NSTextField *cmsLabel(NSString*s){NSTextField*l=[DYThemeLabel wrappingLabelWithString:s];l.font=[NSFont systemFontOfSize:11];l.textColor=DYThemeColor(@"text");return l;}
- (instancetype)initWithManager:(id<PROAPIAccessing>)m renderer:(DYRenderer*)r assetTarget:(id)target {
if((self=[super initWithFrame:NSZeroRect])){_manager=m;_renderer=[r retain];_assetTarget=target;self.identifier=@"managedColor";
_mode=[[DYThemePopUpButton alloc]initWithFrame:NSZeroRect];[_mode addItemsWithTitles:@[@"原有流程(默认)",@"1.8 兼容 · 跟随 FCP",@"1.8 兼容 · 相机 → ACES",@"1.8 兼容 · LUT → ACES",@"一级 CST · 延后输出"]];_mode.target=self;_mode.action=@selector(modeChanged:);_mode.accessibilityLabel=@"色彩管理方式";
_mode=[[DYThemePopUpButton alloc]initWithFrame:NSZeroRect];[_mode addItemsWithTitles:@[@"原有流程(默认)",@"1.8 兼容 · 跟随 FCP",@"1.8 兼容 · 相机 → ACES",@"1.8 兼容 · LUT → ACES",@"1.9 兼容 · 一级与印片后输出",@"全链路 · 输出转换层"]];_mode.target=self;_mode.action=@selector(modeChanged:);_mode.accessibilityLabel=@"色彩管理方式";
_inputLabel=[cmsLabel(@"输入空间")retain];_outputLabel=[cmsLabel(@"输出目标")retain];
_input=[[DYThemePopUpButton alloc]initWithFrame:NSZeroRect];for(NSDictionary*s in DYManagedInputSpaces()){[_input addItemWithTitle:s[@"name"]];_input.lastItem.representedObject=s[@"id"];} _input.target=self;_input.action=@selector(settingsChanged:);_input.accessibilityLabel=@"新版输入空间";
_output=[[DYThemePopUpButton alloc]initWithFrame:NSZeroRect];for(NSDictionary*s in DYManagedOutputSpaces()){[_output addItemWithTitle:s[@"name"]];_output.lastItem.representedObject=s[@"id"];} _output.target=self;_output.action=@selector(settingsChanged:);_output.accessibilityLabel=@"新版输出目标";
@@ -32,17 +32,17 @@ static NSTextField *cmsLabel(NSString*s){NSTextField*l=[DYThemeLabel wrappingLab
- (void)refreshWithState:(NSDictionary*)s context:(NSDictionary*)context {
_refreshing=YES;NSDictionary *saved=[s copy];[_state release];_state=saved;NSInteger mode=s.count?[s[@"mode"]integerValue]:0;[_mode selectItemAtIndex:mode];
NSDictionary *values=s.count&&!DYPrimaryColorState(s)?s:DYManagedColorDefaults();for(NSMenuItem*i in _input.itemArray)if([i.representedObject isEqual:values[@"input"]])[_input selectItem:i];for(NSMenuItem*i in _output.itemArray)if([i.representedObject isEqual:values[@"output"]])[_output selectItem:i];
_input.hidden=_inputLabel.hidden=_output.hidden=_outputLabel.hidden=_gamut.hidden=mode<2||mode==4;_context.hidden=mode==0;_input.enabled=mode==2||mode==3;_output.enabled=mode==2||mode==3;_gamut.enabled=mode==2||mode==3;_gamut.state=[values[@"gamutCompression"]boolValue];_lut.hidden=mode!=3;_inputLabel.stringValue=mode==3?@"LUT 输出":@"输入空间";_outputLabel.stringValue=mode==1?@"跟随宿主":@"输出目标";
_input.hidden=_inputLabel.hidden=_output.hidden=_outputLabel.hidden=_gamut.hidden=mode<2||mode>=4;_context.hidden=mode==0;_input.enabled=mode==2||mode==3;_output.enabled=mode==2||mode==3;_gamut.enabled=mode==2||mode==3;_gamut.state=[values[@"gamutCompression"]boolValue];_lut.hidden=mode!=3;_inputLabel.stringValue=mode==3?@"LUT 输出":@"输入空间";_outputLabel.stringValue=mode==1?@"跟随宿主":@"输出目标";
_help.toolTip=mode==4?@"输入、工作空间及输出均使用下面的一级 CST 设置。一级与印片完成后才执行主输出;其余工具为输出后的 SDR 修饰。请核对上游相机 LUT 与颜色符合,插件无法恢复上游已裁切的信息。":mode==0?@"保留原有处理顺序。选择“延后输出”后,使用一级 CST 的输入和工作空间,在一级与印片之后执行主输出。":mode==1?@"保留 1.8.0 的固定 ACEScct 流程,一级 CST 转换由全局管理接管。宿主已还原的画面无法重新获得原始 Log 信息。":mode==2?@"按所选相机编码解释兼容码值。请确认上游未还原、未自动符合;选择准确输入与输出目标。PQ/HLG 仅支持一级与印片,其他工具用于 SDR。":@"使用输入 LUT,并按“LUT 输出”解释其结果;再进入 ACEScct 和所选输出变换。";
_help.stringValue=mode==0?@"保留原有调色顺序。高级流程按需选择。":mode==4?@"使用一级 CST 设置,在一级与印片之后输出。":mode==1?@"保留 1.8 兼容流程,输入跟随 FCP。":mode==2?@"按所选相机编码解释输入;请核对上游转换。":@"按所选编码解释输入 LUT 的输出。";
_context.stringValue=mode==4?@"输入 CST → 工作域调色与印片 → 输出 CST":context.count?[NSString stringWithFormat:@"%@ → ACEScct → %@",context[@"source"]?:@"未知",context[@"destination"]?:@"未知"]:@"宿主颜色信息将在渲染后显示。";_context.toolTip=mode==4?@"素材编码 → 一级输入 CST → 所选工作域调色与印片 → 一级输出 CST → 宿主。请核对上游相机 LUT 与颜色符合;已裁切信息无法恢复。":_context.stringValue;_refreshing=NO;[self setNeedsLayout:YES];
_help.stringValue=mode==5?@"按模块顺序调色,输出层默认最后,可上下移动。":mode==0?@"保留原有调色顺序。高级流程按需选择。":mode==4?@"使用一级 CST 设置,在一级与印片之后输出。":mode==1?@"保留 1.8 兼容流程,输入跟随 FCP。":mode==2?@"按所选相机编码解释输入;请核对上游转换。":@"按所选编码解释输入 LUT 的输出。";
_context.stringValue=mode==5?@"输入 → 工作域节点 → 输出转换层 → 宿主":mode==4?@"输入 CST → 工作域调色与印片 → 输出 CST":context.count?[NSString stringWithFormat:@"%@ → ACEScct → %@",context[@"source"]?:@"未知",context[@"destination"]?:@"未知"]:@"宿主颜色信息将在渲染后显示。";_context.toolTip=mode==4?@"素材编码 → 一级输入 CST → 所选工作域调色与印片 → 一级输出 CST → 宿主。请核对上游相机 LUT 与颜色符合;已裁切信息无法恢复。":_context.stringValue;_refreshing=NO;[self setNeedsLayout:YES];
}
- (void)setInputLUTPath:(NSString*)path{NSString *saved=[path copy];[_inputLUTPath release];_inputLUTPath=saved;_lut.title=path.length?path.lastPathComponent:@"选择输入 LUT…";_lut.toolTip=path.length?path:@"选择 LUT,并准确指定其输出编码";_lut.accessibilityLabel=path.length?[@"输入 LUT:" stringByAppendingString:path.lastPathComponent]:@"选择输入 LUT";}
- (void)refreshContext{[self refreshWithState:_state context:[_renderer colorContext]];}
- (void)writeState:(NSDictionary*)state {
if(state&&!DYManagedColorValid(state,nil))return;id<FxCustomParameterActionAPI_v4>a=[_manager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{id<FxUndoAPI>undo=[_manager apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:@"更改色彩管理方式"];DYAssetState*assets=[[DYReadAssets(_manager,a.currentTime)copy]autorelease];assets.colorManagement=state;DYWriteAssets(_manager,assets,a.currentTime);if(DYPrimaryColorState(state)&&!DYPrimaryColorState(_state)){DYUniforms u;DYReadUniforms(_manager,a.currentTime,&u);NSMutableDictionary*doc=DYMutablePlist(DYReadTools(_manager,a.currentTime).document);for(NSMutableDictionary*node in doc[@"layers"])DYSeedPrimaryWorkingSpace(node,u.cm.workingTransfer,u.cm.workingGamut);DYFollowPrimaryWorkingSpace(doc,u.cm.workingTransfer,u.cm.workingGamut);DYWriteTools(_manager,doc,a.currentTime);}[undo endUndoGroup];}@finally{[a endAction:self];}[_renderer invalidatePreview];[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:_manager];
}
- (void)modeChanged:(id)sender {if(_refreshing)return;NSInteger mode=_mode.indexOfSelectedItem;_selectionGeneration++;if(mode==3&&(!_inputLUTPath.length||![NSFileManager.defaultManager fileExistsAtPath:_inputLUTPath])){[self refreshWithState:_state context:[_renderer colorContext]];[self selectInputLUTAndEnable:YES];return;}if(!mode){[self writeState:nil];return;}if(mode==4){[self writeState:DYPrimaryColorDefaults()];return;}NSMutableDictionary *s=[[(_state&&!DYPrimaryColorState(_state)?_state:DYManagedColorDefaults())mutableCopy]autorelease];s[@"mode"]=@(mode);[self writeState:s];}
- (void)modeChanged:(id)sender {if(_refreshing)return;NSInteger mode=_mode.indexOfSelectedItem;_selectionGeneration++;if(mode==3&&(!_inputLUTPath.length||![NSFileManager.defaultManager fileExistsAtPath:_inputLUTPath])){[self refreshWithState:_state context:[_renderer colorContext]];[self selectInputLUTAndEnable:YES];return;}if(!mode){[self writeState:nil];return;}if(mode==5){[self writeState:DYUnifiedColorDefaults()];return;}if(mode==4){[self writeState:DYPrimaryColorDefaults()];return;}NSMutableDictionary *s=[[(_state&&!DYPrimaryColorState(_state)?_state:DYManagedColorDefaults())mutableCopy]autorelease];s[@"mode"]=@(mode);[self writeState:s];}
- (void)settingsChanged:(id)sender {if(_refreshing||!_state)return;NSMutableDictionary*s=[[_state mutableCopy]autorelease];s[@"input"]=_input.selectedItem.representedObject;s[@"output"]=_output.selectedItem.representedObject;s[@"gamutCompression"]=@(_gamut.state==NSControlStateValueOn);[self writeState:s];}
- (void)selectInputLUTAndEnable:(BOOL)enable {
NSUInteger generation=_selectionGeneration;NSOpenPanel *panel=[NSOpenPanel openPanel];panel.allowedFileTypes=@[@"cube"];panel.allowsMultipleSelection=NO;panel.canChooseDirectories=NO;panel.message=@"选择输入 LUT,再指定 LUT 的输出编码";
@@ -95,6 +95,12 @@
- (BOOL)renderColorSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state hostPrimaries:(NSInteger)primaries error:(NSError**)error {@synchronized(self){return DYRenderWithPool(error,[&]()->BOOL{
if(state&&![state isKindOfClass:NSDictionary.class])return fail(error,@"色彩管理状态无效。");
NSDictionary*context=DYHostColorContext(src,dst,primaries);@synchronized(_previewLock){[_colorContext release];_colorContext=[context copy];}
if([tools[@"mosaic"][@"enabled"]boolValue]){
if(!DYValidToolDocument(tools))return fail(error,@"局部马赛克设置无效。");
FxImageTile *mosaic=[self sourceByApplyingMosaic:tools source:src registry:dst.deviceRegistryID error:error];if(!mosaic)return NO;
NSMutableDictionary *remaining=[[tools mutableCopy]autorelease];[remaining removeObjectForKey:@"mosaic"];[remaining removeObjectForKey:@"mosaicRenderMask"];
return [self renderColorSource:mosaic destination:dst uniforms:u paths:paths spider:spider tools:remaining colorManagement:state hostPrimaries:primaries error:error];
}
if(tools[@"sharedMasks"]){
if(!DYValidToolDocument(tools))return fail(error,@"调色层或蒙版数据无效。");
FxImageTile *stamped=[self sourceByApplyingStamps:DYSharedMasks(tools) source:src registry:dst.deviceRegistryID error:error];if(!stamped)return NO;
@@ -103,6 +109,7 @@
if(!state.count)return [self renderSource:src destination:dst uniforms:u paths:paths spider:spider tools:tools error:error];
if(!DYManagedColorValid(state,error))return NO;if(!tools)tools=@{@"schema":@2,@"layers":@[],@"baseMasks":@{}};if(!DYValidToolDocument(tools))return fail(error,@"调色层或蒙版数据无效。");
if(tools[@"sharedMasks"])tools=DYResolvedToolDocument(tools);
if(DYUnifiedColorState(state))return [self renderUnifiedSource:src destination:dst uniforms:u paths:paths spider:spider tools:tools hostPrimaries:primaries error:error];
if(DYPrimaryColorState(state))return [self renderPrimarySource:src destination:dst uniforms:u paths:paths spider:spider tools:tools hostPrimaries:primaries error:error];
NSMutableDictionary*entry=[self device:dst.deviceRegistryID error:error];if(!entry)return NO;id<MTLDevice>d=entry[@"device"];id<MTLTexture>source=[src metalTextureForDevice:d];if(!source)return fail(error,@"色彩管理输入纹理不可用。");
uint64_t pixels=uint64_t(source.width)*source.height;if(!pixels||pixels>64ull*1024*1024||pixels*16*8>MAX(768ull*1024*1024,MIN(2ull*1024*1024*1024,d.recommendedMaxWorkingSetSize/2)))return fail(error,@"当前画面超过色彩管理内存预算。");
+26
查看文件
@@ -0,0 +1,26 @@
// Runs on the original frame before grading, then follows the same spatial
// transforms as the picture. Geometry has already been evaluated at render time.
- (FxImageTile*)sourceByApplyingMosaic:(NSDictionary*)tools source:(FxImageTile*)src registry:(uint64_t)registry error:(NSError**)error {
NSDictionary *settings=tools[@"mosaic"];if(![settings[@"enabled"]boolValue])return src;
FxRect image=src.imagePixelBounds,bounds=src.tilePixelBounds;
if(memcmp(&image,&bounds,sizeof(FxRect))!=0){fail(error,@"局部马赛克需要完整源画面。");return nil;}
BOOL face=[settings[@"source"]isEqual:@"face"];
NSDictionary *mask=tools[@"mosaicRenderMask"]?:DYSharedMaskWithID(tools,settings[@"maskID"]);
if(!face&&(!mask||mask[@"stampSource"]||![mask[@"enabled"]boolValue]))return src;
NSMutableDictionary *entry=[self device:registry error:error];if(!entry)return nil;
if(face)[self prepareFaceSupport:src];else{[_faceEntries release];_faceEntries=nil;}
DYToolMaskHeader header{};header.section=face?-102:0;
id<MTLDevice>device=entry[@"device"];id<MTLTexture>input=[src metalTextureForDevice:device];
id<MTLBuffer>buffer=[self maskBuffer:face?@{}:@{@"primary":@[mask]} tile:src device:device header:&header];
MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:input.width height:input.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;
id<MTLTexture>output=[[device newTextureWithDescriptor:desc]autorelease];
id<MTLComputePipelineState>pipeline=[self managedKernel:@"dyLocalMosaic" entry:entry error:error];
if(!input||!buffer||!output||!pipeline){fail(error,@"局部马赛克缓冲区不可用。");return nil;}
// Size is in 1080-line reference pixels, stable under proxy/viewer scaling.
uint32_t block=(uint32_t)MAX(2,round([settings[@"size"]doubleValue]*input.height/1080.));
id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];
[ce setComputePipelineState:pipeline];[ce setTexture:input atIndex:0];[ce setTexture:output atIndex:1];[ce setBuffer:buffer offset:0 atIndex:0];[ce setBytes:&header length:sizeof(header) atIndex:1];[ce setBytes:&block length:sizeof(block) atIndex:2];
[ce dispatchThreads:MTLSizeMake(input.width,input.height,1)threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];
if(cb.status!=MTLCommandBufferStatusCompleted){fail(error,cb.error.localizedDescription);return nil;}
DYExportTile *tile=[[[DYExportTile alloc]initWithTexture:output registry:registry]autorelease];[tile setBounds:bounds origin:src.imageOrigin];[tile setPixelAspect:src.pixelAspect];[tile inheritColorSpace:src.colorSpace];return tile;
}
+2
查看文件
@@ -133,6 +133,8 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData
#include "DYScopeCapture.inc.h"
#include "DYFilmRender.inc.h"
#include "DYPrimaryRender.inc.h"
#include "DYUnifiedRender.inc.h"
#include "DYMosaicRender.inc.h"
#include "DYManagedRender.inc.h"
#include "DYFaceRender.inc.h"
#include "DYToolRender.inc.h"
+1
查看文件
@@ -115,6 +115,7 @@
}@finally{[originalReference release];[skinReference release];[tile release];}
});}}
- (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools error:(NSError**)error {@synchronized(self){
if([tools[@"mosaic"][@"enabled"]boolValue])return fail(error,@"局部马赛克属于空间处理,请保存完整预设。");
if(tools&&!DYValidToolDocument(tools))return fail(error,@"工具或蒙版数据损坏,未更改原工程");DYApplyRemovedBaseTools(&u,tools);paths=DYVisibleBaseToolPaths(paths,tools);if(DYBaseToolRemoved(tools,@"spider"))spider=nil;
if(![tools[@"levelMeasureOnly"]boolValue]&&[tools[@"levelRotation"]doubleValue]!=0)return fail(error,@"水平校正属于空间处理,请保存完整预设。");
for(NSDictionary *mask in DYSharedMasks(tools))if(mask[@"stampSource"]&&[mask[@"enabled"]boolValue])return fail(error,@"仿制图章属于空间处理,请保存完整预设。");
+1
查看文件
@@ -21,6 +21,7 @@ NSDictionary *DYNewTool(NSString *type);
NSDictionary *DYInsertTool(NSMutableDictionary *document,NSString *type,NSString *afterID);
BOOL DYRemoveTool(NSMutableDictionary *document,NSString *nodeID);
NSArray *DYToolDisplayOrder(NSDictionary *document);
NSArray *DYUnifiedRenderOrder(NSDictionary *document);
NSString *DYToolRootAnchor(NSDictionary *document,NSString *nodeID);
NSDictionary *DYNewMask(NSInteger kind);
BOOL DYValidToolDocument(NSDictionary *document);
+11 -1
查看文件
@@ -112,6 +112,12 @@ static NSData *DYValidatedToolData(NSDictionary *doc){
if(![NSPropertyListSerialization propertyList:doc isValidForFormat:NSPropertyListBinaryFormat_v1_0])return nil;
if(![doc isKindOfClass:NSDictionary.class]||(![doc[@"schema"]isEqual:@1]&&![doc[@"schema"]isEqual:@2]&&![doc[@"schema"]isEqual:@3])||![doc[@"layers"]isKindOfClass:NSArray.class]||[doc[@"layers"]count]>DYToolLimit||![doc[@"baseMasks"]isKindOfClass:NSDictionary.class]||[doc[@"baseMasks"]count]>DYToolTypes().count)return nil;
id starter=doc[@"starterTool"],level=doc[@"levelRotation"];
id mosaic=doc[@"mosaic"];
if(mosaic){
if(![mosaic isKindOfClass:NSDictionary.class]||!finiteNumber(mosaic[@"enabled"])||![@[@0,@1]containsObject:mosaic[@"enabled"]]||![@[@"face",@"mask"]containsObject:mosaic[@"source"]]||!finiteNumber(mosaic[@"size"])||[mosaic[@"size"]doubleValue]<4||[mosaic[@"size"]doubleValue]>128)return nil;
if(mosaic[@"maskID"]&&!validID(mosaic[@"maskID"]))return nil;
}
if(doc[@"mosaicRenderMask"]&&!DYValidToolMask(doc[@"mosaicRenderMask"]))return nil;
if(starter&&![DYToolTypes() containsObject:starter]&&![starter isEqual:@"cst"])return nil;
if(level&&(!finiteNumber(level)||fabs([level doubleValue])>M_PI))return nil;
id measured=doc[@"levelMeasureOnly"],reference=doc[@"levelReference"];
@@ -132,6 +138,7 @@ static NSData *DYValidatedToolData(NSDictionary *doc){
// Anchors are stable identities, never an array index or a translated title.
// Reject unknown anchors/cycles so layout, rendering and undo share one order.
for(NSDictionary *node in doc[@"layers"]){id after=node[@"after"];if(!after)continue;if([doc[@"schema"]isEqual:@1]||![after isKindOfClass:NSString.class])return nil;NSMutableSet *seen=[NSMutableSet setWithObject:node[@"id"]];while(after){if([after hasPrefix:@"base:"]){if(![DYToolTypes()containsObject:[after substringFromIndex:5]])return nil;break;}if([seen containsObject:after])return nil;[seen addObject:after];NSDictionary *parent=DYToolWithID(doc,after);if(!parent)return nil;after=parent[@"after"];}}
id outputAfter=doc[@"outputAfter"];if(outputAfter&&(![outputAfter isKindOfClass:NSString.class]||(![outputAfter isEqual:@"tail"]&&![DYToolDisplayOrder(doc)containsObject:outputAfter])))return nil;
NSUInteger totalKeys=0;for(NSDictionary *mask in shared)totalKeys+=[mask[@"keys"]count];for(NSArray *masks in [doc[@"baseMasks"]allValues])for(NSDictionary *mask in masks)totalKeys+=[mask[@"keys"]count];for(NSDictionary *node in doc[@"layers"])for(NSDictionary *mask in node[@"masks"])totalKeys+=[mask[@"keys"]count];if(totalKeys>65536)return nil;NSData *bounded=[NSPropertyListSerialization dataWithPropertyList:doc format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];return bounded.length<=24*1024*1024?bounded:nil;
}
BOOL DYValidToolDocument(NSDictionary *doc){return DYValidatedToolData(doc)!=nil;}
@@ -154,8 +161,9 @@ NSDictionary *DYToolWithID(NSDictionary *doc,NSString *ID){for(NSDictionary *n i
static void DYAppendToolChildren(NSDictionary *doc,NSString *parent,NSMutableArray *order,NSMutableSet *seen){for(NSDictionary *node in doc[@"layers"])if([node[@"after"]isEqual:parent]&&![seen containsObject:node[@"id"]]){[seen addObject:node[@"id"]];[order addObject:node[@"id"]];DYAppendToolChildren(doc,node[@"id"],order,seen);}}
NSArray *DYToolDisplayOrder(NSDictionary *doc){NSMutableArray *order=[NSMutableArray array];NSMutableSet *seen=[NSMutableSet set];for(NSString *type in DYToolTypes()){NSString *base=[@"base:" stringByAppendingString:type];[order addObject:base];DYAppendToolChildren(doc,base,order,seen);}for(NSDictionary *node in doc[@"layers"])if(!node[@"after"]&&![seen containsObject:node[@"id"]]){[seen addObject:node[@"id"]];[order addObject:node[@"id"]];DYAppendToolChildren(doc,node[@"id"],order,seen);}return order;}
NSString *DYToolRootAnchor(NSDictionary *doc,NSString *ID){NSMutableSet *seen=[NSMutableSet set];NSDictionary *node=DYToolWithID(doc,ID);while(node[@"after"]){NSString *after=node[@"after"];if([after hasPrefix:@"base:"])return after;if([seen containsObject:after])return nil;[seen addObject:after];node=DYToolWithID(doc,after);}return @"tail";}
NSArray *DYUnifiedRenderOrder(NSDictionary *doc){NSMutableArray *order=[NSMutableArray arrayWithArray:DYToolDisplayOrder(doc)];NSString *after=doc[@"outputAfter"]?:@"tail";NSUInteger index=[order indexOfObject:after];[order insertObject:@"output" atIndex:index==NSNotFound?order.count:index+1];return order;}
NSDictionary *DYInsertTool(NSMutableDictionary *doc,NSString *type,NSString *after){if(!DYValidToolDocument(doc)||[doc[@"layers"]count]>=DYToolLimit)return nil;if(!([after hasPrefix:@"base:"]&&[DYToolTypes()containsObject:[after substringFromIndex:5]])&&!DYToolWithID(doc,after))return nil;NSDictionary *fresh=DYNewTool(type);if(!fresh)return nil;NSMutableDictionary *node=DYMutablePlist(fresh);node[@"after"]=after;NSMutableArray *layers=doc[@"layers"];for(NSMutableDictionary *old in layers)if([old[@"after"]isEqual:after])old[@"after"]=node[@"id"];NSUInteger index=0;NSDictionary *parent=DYToolWithID(doc,after);if(parent)index=[layers indexOfObjectIdenticalTo:parent]+1;[layers insertObject:node atIndex:MIN(index,layers.count)];if(![doc[@"schema"]isEqual:@3])doc[@"schema"]=@2;return node;}
BOOL DYRemoveTool(NSMutableDictionary *doc,NSString *ID){NSMutableDictionary *node=(id)DYToolWithID(doc,ID);if(!node)return NO;NSString *after=node[@"after"];for(NSMutableDictionary *child in doc[@"layers"])if([child[@"after"]isEqual:ID]){if(after)child[@"after"]=after;else[child removeObjectForKey:@"after"];}[doc[@"layers"]removeObject:node];return YES;}
BOOL DYRemoveTool(NSMutableDictionary *doc,NSString *ID){NSMutableDictionary *node=(id)DYToolWithID(doc,ID);if(!node)return NO;NSString *after=node[@"after"];if([doc[@"outputAfter"]isEqual:ID])doc[@"outputAfter"]=after?:@"tail";for(NSMutableDictionary *child in doc[@"layers"])if([child[@"after"]isEqual:ID]){if(after)child[@"after"]=after;else[child removeObjectForKey:@"after"];}[doc[@"layers"]removeObject:node];return YES;}
NSArray *DYSharedMasks(NSDictionary *doc){return [doc[@"sharedMasks"]isKindOfClass:NSArray.class]?doc[@"sharedMasks"]:@[];}
NSDictionary *DYSharedMaskWithID(NSDictionary *doc,NSString *ID){for(NSDictionary *mask in DYSharedMasks(doc))if([mask[@"id"]isEqual:ID])return mask;return nil;}
static NSArray *DYRawMasksForTool(NSDictionary *doc,NSString *ID){return [ID hasPrefix:@"base:"]?doc[@"baseMasks"][[ID substringFromIndex:5]]?:@[]:DYToolWithID(doc,ID)[@"masks"]?:@[];}
@@ -362,6 +370,8 @@ NSDictionary *DYToolRenderSnapshot(NSDictionary *doc,CMTime t){
return result;
};
NSMutableDictionary *out=[[doc mutableCopy]autorelease],*base=[NSMutableDictionary dictionary];
NSString *mosaicID=doc[@"mosaic"][@"maskID"];
for(NSDictionary *mask in shared)if(!mask[@"stampSource"]&&[mask[@"id"]isEqual:mosaicID])out[@"mosaicRenderMask"]=resolve(@[mask]).firstObject;
for(NSString *type in doc[@"baseMasks"])base[type]=resolve(doc[@"baseMasks"][type]);out[@"baseMasks"]=base;
NSMutableArray *layers=[NSMutableArray array];
for(NSDictionary *node in doc[@"layers"]){NSMutableDictionary *layer=[[node mutableCopy]autorelease];layer[@"masks"]=resolve(node[@"masks"]);[layers addObject:layer];}
@@ -0,0 +1,41 @@
// Production render tests for the ordered chain and spatial privacy operator.
{
NSDictionary *v4=DYUnifiedColorDefaults();run.need(@"unified-v4-valid-and-distinct-from-v3",DYManagedColorValid(v4,nil)&&DYUnifiedColorState(v4)&&![v4 isEqual:DYPrimaryColorDefaults()]);
NSMutableDictionary *doc=DYMutablePlist(DYInitialToolDocument(nil));run.record(@"unified-default-output-is-last",[DYUnifiedRenderOrder(doc).lastObject isEqual:@"output"]);
NSDictionary *node=DYInsertTool(doc,@"curve",@"base:hsl");doc[@"outputAfter"]=node[@"id"];
NSArray *order=DYUnifiedRenderOrder(doc);run.record(@"unified-output-follows-stable-uuid",[order indexOfObject:@"output"]==[order indexOfObject:node[@"id"]]+1&&DYValidToolDocument(doc));
DYRemoveTool(doc,node[@"id"]);run.record(@"unified-deleting-anchor-keeps-valid-output-order",DYValidToolDocument(doc)&&[doc[@"outputAfter"]isEqual:@"base:hsl"]);
doc[@"outputAfter"]=@"unknown";run.record(@"unified-rejects-unknown-output-anchor",!DYValidToolDocument(doc));doc=DYMutablePlist(DYInitialToolDocument(nil));
const NSUInteger w=64,h=48;DYDiagnosticTile *src=[[[DYDiagnosticTile alloc]initWithDevice:gpu width:w height:h]autorelease],*dst=[[[DYDiagnosticTile alloc]initWithDevice:gpu width:w height:h]autorelease];
auto decode=[](float x){return x<=.04045f?x/12.92f:powf((x+.055f)/1.055f,2.4f);};
Pixels chart(w*h*4);for(NSUInteger i=0;i<w*h;i++){chart[i*4]=decode(-.04f);chart[i*4+1]=decode(.18f+(i%w)/100.f);chart[i*4+2]=decode(4.f);chart[i*4+3]=1;}
[[src metalTextureForDevice:gpu]replaceRegion:MTLRegionMake2D(0,0,w,h)mipmapLevel:0 withBytes:chart.data()bytesPerRow:w*8];
DYRenderer *renderer=[[[DYRenderer alloc]init]autorelease];DYUniforms u=defaults;u.skinProtection.x=0;u.cm.configured=1;u.cm.inputTransfer=u.cm.workingTransfer=u.cm.outputTransfer=20;u.cm.inputGamut=u.cm.workingGamut=u.cm.outputGamut=22;u.cm.toneMapping=0;
auto frame=[&](DYUniforms values,NSDictionary *document,NSString *name){NSError *e=nil;BOOL ok=[renderer renderSource:src destination:dst uniforms:values paths:@{} spider:nil tools:document colorManagement:v4 hostPrimaries:kFxColorPrimaries_Rec709 error:&e];run.need(name,ok,@{@"error":reason(e)});return read(dst,gpu);};
Pixels plain=frame(u,doc,@"unified-neutral-wide-chain-renders");run.record(@"unified-neutral-preserves-negative-and-superwhite",fabs((float)plain[0]+.04)<.002&&fabs((float)plain[2]-4)<.01&&difference(plain,plain).nonfinite==0);
DYUniforms changed=u;changed.hslHueA.x=20;changed.hslHueB.x=20;Pixels modified=frame(changed,doc,@"unified-HSL-before-output-accepts-linear-domain");run.record(@"unified-active-bounded-tool-carries-superwhite-residual",modified[2]>2.9&&difference(plain,modified).nonfinite==0);
NSMutableDictionary *zero=DYMutablePlist(DYNewMask(DYMaskRectangle));DYMaskParameters p=DYMaskAtTime(zero,kCMTimeZero);p.strength=0;zero[@"parameters"]=[NSData dataWithBytes:&p length:sizeof(p)];doc[@"baseMasks"][@"hsl"]=@[zero];
Pixels masked=frame(changed,doc,@"unified-zero-mask");run.record(@"unified-zero-mask-is-exact-neutral",difference(masked,plain).maximum==0);[doc[@"baseMasks"]removeObjectForKey:@"hsl"];
changed.cm.outputTransfer=1002;changed.cm.toneMapping=1;changed.hslSatA.x=40;Pixels last=frame(changed,doc,@"unified-last-output");doc[@"outputAfter"]=@"base:primary";Pixels middle=frame(changed,doc,@"unified-middle-output");run.record(@"unified-moving-output-changes-actual-domain-order",difference(last,middle).maximum>.001,@{@"difference":@(difference(last,middle).maximum)});
DYDiagnosticManager *host=[[[DYDiagnosticManager alloc]init]autorelease];DYCreateParameters(host,nil);DYAssetState *assets=[[[DYAssetState alloc]init]autorelease];assets.colorManagement=v4;DYWriteAssets(host,assets,kCMTimeZero);
DYInspector *view=[[[DYInspector alloc]initWithAPIManager:host]autorelease];[view refresh];[view setFrameSize:NSMakeSize(400,400)];[view layoutSubtreeIfNeeded];NSDictionary *output=nil;for(NSDictionary *card in [view valueForKey:@"cards"])if([card[@"section"][@"key"]isEqual:@"output"])output=card;
run.record(@"unified-inspector-output-visible-at-chain-tail",output&&![output[@"view"]isHidden]&&NSMaxY([output[@"view"]frame])>NSMaxY([[[view valueForKey:@"cards"]firstObject][@"view"]frame]));
[(NSButton*)output[@"repeatButton"]performClick:nil];run.record(@"unified-output-arrow-persists-and-creates-one-undo",[DYReadTools(host,kCMTimeZero).document[@"outputAfter"]isEqual:@"base:base"]&&host->_undoStarts==1&&host->_undoEnds==1);
}
{
const NSUInteger w=128,h=96;DYDiagnosticTile *src=[[[DYDiagnosticTile alloc]initWithDevice:gpu width:w height:h]autorelease],*dst=[[[DYDiagnosticTile alloc]initWithDevice:gpu width:w height:h]autorelease];Pixels chart(w*h*4);
for(NSUInteger y=0;y<h;y++)for(NSUInteger x=0;x<w;x++){NSUInteger i=(y*w+x)*4;chart[i]=x/double(w);chart[i+1]=y/double(h);chart[i+2]=(x%2)*.4;chart[i+3]=1;}
[[src metalTextureForDevice:gpu]replaceRegion:MTLRegionMake2D(0,0,w,h)mipmapLevel:0 withBytes:chart.data()bytesPerRow:w*8];
DYRenderer *renderer=[[[DYRenderer alloc]init]autorelease];DYUniforms u=defaults;u.primarySectionEnabled=0;u.skinProtection.x=0;
NSMutableDictionary *doc=DYMutablePlist(DYInitialToolDocument(nil));NSMutableDictionary *mask=(id)DYAddSharedMask(doc,DYMaskRectangle);DYMaskParameters p=DYMaskAtTime(mask,kCMTimeZero);p.width=p.height=.4;p.centerX=.25;p.centerY=.5;p.feather=0;mask[@"parameters"]=[NSData dataWithBytes:&p length:sizeof(p)];
doc[@"mosaic"]=@{@"source":@"mask",@"maskID":mask[@"id"],@"enabled":@YES,@"size":@96};NSError *e=nil;
auto frame=[&](NSDictionary *document,NSString *name){BOOL ok=[renderer renderSource:src destination:dst uniforms:u paths:@{} spider:nil tools:document colorManagement:nil hostPrimaries:kFxColorPrimaries_Rec709 error:&e];run.need(name,ok,@{@"error":reason(e)});return read(dst,gpu);};
Pixels baseline=frame(DYInitialToolDocument(nil),@"mosaic-baseline");Pixels first=frame(DYToolRenderSnapshot(doc,kCMTimeZero),@"mosaic-shared-rectangle-render");
double inside=0,outside=0;for(NSUInteger y=0;y<h;y++)for(NSUInteger x=0;x<w;x++)for(int c=0;c<3;c++){double delta=fabs((float)first[(y*w+x)*4+c]-(float)baseline[(y*w+x)*4+c]);if(x>15&&x<48&&y>35&&y<60)inside=MAX(inside,delta);if(x>75)outside=MAX(outside,delta);}
run.record(@"mosaic-changes-selection-and-preserves-outside",inside>.05&&outside==0,@{@"inside":@(inside),@"outside":@(outside)});
DYMaskParameters moved=p;moved.centerX=.75;mask[@"keys"]=@[DYMaskKey(kCMTimeZero,p,YES,1),DYMaskKey(CMTimeMake(1,1),moved,YES,1)];
Pixels tracked=frame(DYToolRenderSnapshot(doc,CMTimeMake(1,1)),@"mosaic-follow-existing-tracking");run.record(@"mosaic-tracked-selection-vacates-previous-region",tracked[(48*w+31)*4+2]==baseline[(48*w+31)*4+2]&&tracked[(48*w+95)*4+2]!=baseline[(48*w+95)*4+2]);
doc[@"mosaic"]=@{@"source":@"mask",@"maskID":NSUUID.UUID.UUIDString,@"enabled":@YES,@"size":@96};Pixels missing=frame(DYToolRenderSnapshot(doc,kCMTimeZero),@"mosaic-missing-mask");run.record(@"mosaic-missing-mask-does-not-cover-whole-frame",difference(missing,baseline).maximum==0);
NSURL *cube=[NSURL fileURLWithPath:[runtime stringByAppendingPathComponent:@"mosaic-refused.cube"]];run.record(@"mosaic-refuses-incomplete-cube-export",![renderer exportLUT:cube uniforms:u paths:@{} spider:nil tools:doc colorManagement:nil error:&e]&&e);
NSMutableDictionary *bad=DYMutablePlist(doc);bad[@"mosaic"][@"size"]=@0;run.record(@"mosaic-invalid-block-size-rejected",!DYValidToolDocument(bad));
}
+80
查看文件
@@ -0,0 +1,80 @@
// V4: stable author order, one movable output boundary, explicit node domains.
- (BOOL)renderUnifiedSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools hostPrimaries:(NSInteger)primaries error:(NSError**)error {
if(tools[@"sharedMasks"])tools=DYResolvedToolDocument(tools);
NSMutableDictionary*entry=[self device:dst.deviceRegistryID error:error];if(!entry)return NO;id<MTLDevice>d=entry[@"device"];id<MTLTexture>source=[src metalTextureForDevice:d];if(!source)return fail(error,@"一级 CST 输入纹理不可用。");
uint64_t pixels=uint64_t(source.width)*source.height;if(!pixels||pixels>64ull*1024*1024||pixels*16*8>MAX(768ull*1024*1024,MIN(2ull*1024*1024*1024,d.recommendedMaxWorkingSetSize/2)))return fail(error,@"当前画面超过一级 CST 内存预算。");
BOOL inputEnabled=u.inputSectionEnabled>.5;DYCMSettings global=u.cm;BOOL root=u.primarySectionEnabled>.5&&!DYBaseToolRemoved(tools,@"primary");DYApplyRemovedBaseTools(&u,tools);u.cm=global;int wt=lroundf(u.cm.workingTransfer),wg=lroundf(u.cm.workingGamut);
NSMutableArray*pool=[NSMutableArray array];NSCountedSet*pinned=[NSCountedSet set];id<MTLTexture>current=nil;
auto next=[&]()->id<MTLTexture>{for(id<MTLTexture>t in pool)if(t!=current&&![pinned containsObject:t])return t;MTLTextureDescriptor*td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:source.width height:source.height mipmapped:NO];td.storageMode=MTLStorageModePrivate;td.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite|MTLTextureUsageRenderTarget;id<MTLTexture>t=[d newTextureWithDescriptor:td];if(t){[pool addObject:t];[t release];}return t;};
auto dispatch=[&](NSString*name,const void*params,NSUInteger length,const void*extra=nullptr,NSUInteger extraLength=0){id<MTLTexture>out=next();if(!out)return fail(error,@"无法分配一级 CST 缓冲区。");BOOL ok=[self managedDispatch:name textures:@[current,out] data:params length:length extra:extra extraLength:extraLength entry:entry error:error];if(ok)current=out;return ok;};
auto transform=[&](CSTParams p){if(p.inputTransfer==p.outputTransfer&&p.inputGamut==p.outputGamut&&!p.toneMapping)return YES;return dispatch(@"dyPrimaryCST",&p,sizeof(p));};
auto tile=[&](id<MTLTexture>t){DYExportTile*v=[[[DYExportTile alloc]initWithTexture:t registry:d.registryID]autorelease];[v setBounds:src.tilePixelBounds origin:src.imageOrigin];[v setPixelAspect:src.pixelAspect];return v;};
auto blend=[&](id<MTLTexture>before,NSArray*masks,float amount,NSString*type){if(!masks.count&&amount>=1)return YES;id<MTLTexture>out=next();if(!out)return fail(error,@"无法分配一级混合缓冲区。");DYToolMaskHeader h{};id<MTLBuffer>mb=[self maskBuffer:@{type:masks?:@[]} tile:src device:d header:&h];h.section=(int)[DYToolTypes()indexOfObject:type];DYCSTMixParams p={{wg,wt,2,20,0},{2,20,wg,wt,0},amount};id<MTLComputePipelineState>pipeline=[self managedKernel:@"dyPrimaryBlend" entry:entry error:error];if(!pipeline||!mb)return NO;id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:pipeline];[ce setTexture:before atIndex:0];[ce setTexture:current atIndex:1];[ce setTexture:out atIndex:2];[ce setBuffer:mb offset:0 atIndex:0];[ce setBytes:&h length:sizeof(h) atIndex:1];[ce setBytes:&p length:sizeof(p) atIndex:2];[ce dispatchThreads:MTLSizeMake(source.width,source.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription);current=out;return YES;};
auto grade=[&](DYUniforms values,NSArray*masks,BOOL local){if(values.primarySectionEnabled<.5||values.cm.mix<=0)return YES;DYUniforms neutral=values;neutral.inputSectionEnabled=neutral.cm.outputEnabled=0;BOOL gradeNeutral=identityCM(neutral);if(!local&&gradeNeutral)return YES;if(local&&identityCM(values))return YES;
DayuRenderParams p=DYCMRender(values.cm);p.input.toneMapping=0;if((int)lroundf(values.cm.workingTransfer)==20){p.reserved|=8;p.basis.colorspace=10;p.basisInput={(int)lroundf(values.cm.workingGamut),20,(int)lroundf(values.cm.workingGamut),10,0};p.basisOutput={(int)lroundf(values.cm.workingGamut),10,(int)lroundf(values.cm.workingGamut),20,0};}CSTParams back={wg,wt,wg,wt,0};
if(local){p.stages=(values.inputSectionEnabled>.5?1:0)|(gradeNeutral?0:2)|(values.cm.outputEnabled>.5?4:0);back={values.cm.outputEnabled>.5?(int)lroundf(values.cm.outputGamut):(int)lroundf(values.cm.workingGamut),values.cm.outputEnabled>.5?(int)lroundf(values.cm.outputTransfer):(int)lroundf(values.cm.workingTransfer),wg,wt,0};}
else{p.stages=2;}
id<MTLTexture>before=current;[pinned addObject:before];BOOL ok=dispatch(@"dyPrimaryGrade",&p,sizeof(p),&back,sizeof(back));if(ok)ok=blend(before,masks,values.cm.mix,@"primary");[pinned removeObject:before];return ok;
};
auto print=[&](DYUniforms values,NSArray*masks){if(!DYFilmPrintActive(values))return YES;NSArray*names=@[@"",@"kodak_2383",@"kodak_2393",@"kodak_2302_bw",@"fuji_3510",@"fuji_3513",@"fuji_3519",@"fuji_3521",@"agfa_cp30"];NSString*path=[[NSBundle bundleForClass:self.class]pathForResource:names[(int)values.filmPrint.x] ofType:@"dylut" inDirectory:@"PrintLooks"];id<MTLTexture>cube=path?[self lut:path entry:entry error:error]:nil;if(!cube)return fail(error,@"印片资源不可用。");id<MTLTexture>before=current;[pinned addObject:before];BOOL ok=transform({wg,wt,2,1,0});float amount=values.filmPrint.y*values.film.mix;if(ok){id<MTLTexture>out=next();ok=out&&[self managedDispatch:@"dyManagedPrint" textures:@[current,cube,out] data:&amount length:4 extra:nullptr extraLength:0 entry:entry error:error];if(ok)current=out;}if(ok)ok=transform({2,1,wg,wt,0});if(ok)ok=blend(before,masks,1,@"film");[pinned removeObject:before];return ok;};
// Recover only the pre-existing explicit code-value carrier. No display
// transform or host-profile-to-709 conversion precedes the declared input.
current=source;id<MTLTexture>carrier=next();uint32_t noLUT=0;if(!carrier||![self managedDispatch:@"dyManagedCarrier" textures:@[current,carrier,entry[@"identity"]] data:&noLUT length:4 extra:nullptr extraLength:0 entry:entry error:error])return NO;current=carrier;
if(inputEnabled&&!transform({(int)lroundf(u.cm.inputGamut),(int)lroundf(u.cm.inputTransfer),wg,wt,0}))return NO;
// Preserve the original working image for source-referenced operations.
id<MTLTexture>originalWorking=current;[pinned addObject:originalWorking];int initialGamut=wg,initialTransfer=wt;
auto isolated=[&](NSString *type,DYUniforms values,NSDictionary *nodePaths,NSData *mesh,NSArray *masks){
NSMutableDictionary *node=[NSMutableDictionary dictionaryWithDictionary:DYNewTool(type)];NSMutableDictionary *v=[NSMutableDictionary dictionary];
for(NSDictionary *descriptor in DYBaseToolDescriptors(type))if([descriptor[@"offset"]integerValue]>=0)v[descriptor[@"key"]]=@(*(float*)((uint8_t*)&values+[descriptor[@"offset"]unsignedIntegerValue]));
node[@"values"]=v;node[@"paths"]=nodePaths?:@{};node[@"masks"]=@[];if(mesh)node[@"spider"]=mesh;
node[@"filmFrameKey"]=@(values.filmFrameKey);
if(DYToolIsNeutral(node))return YES;
id<MTLTexture>before=current;[pinned addObject:before];BOOL ok=YES;
if([type isEqual:@"lens"]){id<MTLTexture>out=next();ok=out&&[self renderLens:tile(current) destination:tile(out) uniforms:values masks:@[] entry:entry error:error];if(ok)current=out;}
else {
// Creative Rec.709 LUT/film and skin models declare a local reference domain.
// All other legacy controls operate on the current working RGB code values.
BOOL reference=[@[@"look",@"film",@"skin"]containsObject:type];
int domainGamut=reference?22:wg,domainTransfer=reference?1001:wt;
if(reference)ok=transform({wg,wt,domainGamut,domainTransfer,0});
id<MTLTexture>raw=current;[pinned addObject:raw];
if(ok)ok=dispatch(@"dyUnifiedBridgeIn",nullptr,0);
id<MTLTexture>bounded=current;[pinned addObject:bounded];
// A source-referenced skin node compares to the original image in this same
// domain, never to a previous frame or an unrelated cached display image.
id<MTLTexture>referenceTexture=bounded;
if(ok&&[type isEqual:@"skin"]){current=originalWorking;ok=transform({initialGamut,initialTransfer,domainGamut,domainTransfer,0})&&dispatch(@"dyUnifiedBridgeIn",nullptr,0);referenceTexture=current;[pinned addObject:referenceTexture];current=bounded;}
if(ok){id<MTLTexture>out=next();_managedFinishing=YES;@try{ok=out&&[self renderExtraTool:node source:tile(bounded) original:tile(referenceTexture) destination:tile(out) entry:entry error:error];}@finally{_managedFinishing=NO;}if(ok)current=out;}
if(referenceTexture!=bounded)[pinned removeObject:referenceTexture];[pinned removeObject:bounded];
if(ok){id<MTLTexture>out=next();ok=out&&[self managedDispatch:@"dyUnifiedBridgeOut" textures:@[raw,current,out] data:nullptr length:0 extra:nullptr extraLength:0 entry:entry error:error];if(ok)current=out;}
[pinned removeObject:raw];
if(ok&&reference)ok=transform({domainGamut,domainTransfer,wg,wt,0});
}
if(ok)ok=blend(before,masks,1,type);[pinned removeObject:before];return ok;
};
for(NSString *ID in DYUnifiedRenderOrder(tools)){
if([ID isEqual:@"output"]){
if(u.cm.outputEnabled>.5){CSTParams output={wg,wt,(int)lroundf(u.cm.outputGamut),(int)lroundf(u.cm.outputTransfer),0};
if(u.cm.toneMapping>.5)output.toneMapping=(wt>1000?2:0)+(output.outputTransfer>1000?1:0);
if(!transform(output))return NO;wg=output.outputGamut;wt=output.outputTransfer;
}continue;
}
BOOL base=[ID hasPrefix:@"base:"];NSDictionary *node=base?nil:DYToolWithID(tools,ID);NSString *type=base?[ID substringFromIndex:5]:node[@"type"];
if(base&&DYBaseToolRemoved(tools,type))continue;
DYUniforms values=base?u:DYToolUniforms(node);NSArray *masks=base?tools[@"baseMasks"][type]:node[@"masks"];
if([type isEqual:@"primary"]){values.inputSectionEnabled=values.cm.outputEnabled=0;values.cm.workingTransfer=wt;values.cm.workingGamut=wg;if(!grade(values,masks,NO))return NO;continue;}
if([type isEqual:@"film"]){if(!print(values,masks))return NO;values.filmPrint.x=0;}
if(!isolated(type,values,base?DYVisibleBaseToolPaths(paths,tools):node[@"paths"],base?spider:node[@"spider"],masks))return NO;
}
[pinned removeObject:originalWorking];
// Final host adaptation is separate from the movable output node. Cube uses
// the exact current code domain after the same ordered operations.
if(_exporting){if(!dispatch(@"dyPrimaryCodeOutput",nullptr,0))return NO;}
else {
if(!transform({wg,wt,22,20,0}))return NO;[self managedPreview:current origin:src.imageOrigin entry:entry];
CGColorSpaceRef from=CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearSRGB),to=DYManagedTileSpace(dst,primaries);
DYColorProfile *profile=to?[[[DYColorProfile alloc]initWithSource:from target:to error:error]autorelease]:nil;CGColorSpaceRelease(from);if(to)CGColorSpaceRelease(to);
if(!profile)return fail(error,@"宿主未提供明确的目标颜色空间。");id<MTLTexture>out=next();if(!out||![self managedProfile:profile input:current output:out entry:entry error:error])return NO;current=out;
}
_managedFinishing=YES;@try{return [self copyTile:tile(current) to:dst entry:entry error:error];}@finally{_managedFinishing=NO;}
}
+5 -4
查看文件
@@ -79,10 +79,10 @@ NSRect bounds=NSMakeRect(0,0,size.width,size.height),v=_hasViewport?NSIntersecti
if(_capture&&![_capture capturing])_capture=nil;
[_areas removeAllObjects];if(!_bridge||v.size.width<100||v.size.height<80)return;
// Only tools that benefit from direct image interaction belong on the canvas.
NSArray *types=@[@"curve",@"lens",@"skin",@"look",@"whiteBalance",@"cloneStamp",@"level"],*titles=@[@"曲线",@"畸变修复",@"肤色",@"LUT",@"白平衡吸管",@"仿制图章",@"水平校正"],*symbols=@[@"point.topleft.down.to.point.bottomright.curvepath",@"pincushion-grid",@"person.crop.circle",@"square.stack.3d.up",@"eyedropper",@"clone-stamp",@"level"];
CGFloat railScale=MIN(s,v.size.width/520.),y=NSMaxY(v)-33*railScale,w=36*railScale;
CGFloat x=NSMaxX(v)-516*railScale;
_rail=NSMakeRect(x,y,396*railScale,25*railScale);
NSArray *types=@[@"curve",@"lens",@"skin",@"look",@"whiteBalance",@"cloneStamp",@"level",@"mosaic"],*titles=@[@"曲线",@"畸变修复",@"肤色",@"LUT",@"白平衡吸管",@"仿制图章",@"水平校正",@"局部马赛克"],*symbols=@[@"point.topleft.down.to.point.bottomright.curvepath",@"pincushion-grid",@"person.crop.circle",@"square.stack.3d.up",@"eyedropper",@"clone-stamp",@"level",@"square.grid.3x3.fill"];
CGFloat railScale=MIN(s,v.size.width/560.),y=NSMaxY(v)-33*railScale,w=36*railScale;
CGFloat x=NSMaxX(v)-556*railScale;
_rail=NSMakeRect(x,y,436*railScale,25*railScale);
if(_levelMode){
NSArray *labels=@[@"水平",@"垂直",@"重置",@"仅测量"];
for(NSInteger i=0;i<4;i++){
@@ -157,6 +157,7 @@ NSRect bounds=NSMakeRect(0,0,size.width,size.height),v=_hasViewport?NSIntersecti
[NSGraphicsContext restoreGraphicsState];
}
- (void)activateTool:(NSString*)type{
if([type isEqual:@"mosaic"]){[self finishCapture];_stampArmed=NO;_levelMode=0;[_bridge requestMosaicMenu];return;}
if([type isEqual:@"level"]){[self finishCapture];_stampArmed=NO;_levelMode=_levelMode?0:1;return;}
BOOL returningFromLevel=_levelMode!=0;_levelMode=0;
if([type isEqual:@"cloneStamp"]){_stampArmed=!_stampArmed;return;}
@@ -12,7 +12,7 @@
publish();int undo=base->_undoStarts;NSDictionary *initial=[[base->_values copy]autorelease];
NSMutableSet *types=[NSMutableSet set];NSInteger masks=0;CGFloat lastX=-1,y=-1;BOOL horizontal=YES;
for(NSDictionary *a in [controls valueForKey:@"areas"]){if([a[@"kind"]isEqual:@"mask"])masks++;if([a[@"kind"]isEqual:@"tool"]){NSRect r=[a[@"rect"]rectValue];if(lastX>=0)horizontal&=r.origin.x>lastX&&r.origin.y==y;lastX=r.origin.x;y=r.origin.y;[types addObject:a[@"toolType"]];}}
run.record(@"viewer-lower-right-rail-has-seven-image-tools-and-three-persistent-mask-shapes",horizontal&&lastX>size.width*.8&&y>size.height*.9&&[types isEqual:[NSSet setWithArray:@[@"curve",@"lens",@"skin",@"look",@"whiteBalance",@"cloneStamp",@"level"]]]&&masks==3&&[[controls valueForKey:@"panels"]count]==0);
run.record(@"viewer-lower-right-rail-has-eight-image-tools-and-three-persistent-mask-shapes",horizontal&&lastX>size.width*.8&&y>size.height*.9&&[types isEqual:[NSSet setWithArray:@[@"curve",@"lens",@"skin",@"look",@"whiteBalance",@"cloneStamp",@"level",@"mosaic"]]]&&masks==3&&[[controls valueForKey:@"panels"]count]==0);
NSDictionary *stamp=areaFor(controls,@"tool",@"cloneStamp");
click(stamp);BOOL armed=controls.stampArmed;click(stamp);
run.record(@"viewer-stamp-arms-and-disarms-without-changing-the-grade",armed&&!controls.stampArmed&&[initial isEqual:base->_values]&&base->_undoStarts==undo);
@@ -20,6 +20,7 @@
// Call before the owning plug-in releases this object during teardown.
- (void)invalidate;
- (void)requestWorkspace;
- (void)requestMosaicMenu;
- (void)requestWorkspacePage:(NSString *)page;
- (void)requestMask:(NSInteger)kind;
- (void)requestTool:(NSString*)type;
@@ -104,6 +105,38 @@ static BOOL DYViewerSanitizeValue(NSDictionary *d,double input,double *output) {
if(![DYToolTypes()containsObject:type])return;
dispatch_async(dispatch_get_main_queue(),^{id manager=nil;@synchronized(self){if(!self->_invalidated)manager=self->_apiManager;}if(manager)[NSNotificationCenter.defaultCenter postNotificationName:@"DYViewerToolRequested" object:manager userInfo:@{@"type":type}];});
}
- (void)applyMosaicMenu:(NSMenuItem*)item {
id manager=nil;@synchronized(self){if(!_invalidated)manager=_apiManager;}if(!manager)return;
id<FxCustomParameterActionAPI_v4>a=[manager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];[a startAction:self];
@try{
NSMutableDictionary *doc=DYMutablePlist(DYReadTools(manager,a.currentTime).document);
NSMutableDictionary *settings=[NSMutableDictionary dictionaryWithDictionary:doc[@"mosaic"]?:@{@"enabled":@NO,@"source":@"face",@"size":@32}];
[settings addEntriesFromDictionary:item.representedObject];
if([settings[@"source"]isEqual:@"mask"]&&!DYSharedMaskWithID(doc,settings[@"maskID"]))return;
doc[@"mosaic"]=settings;id<FxUndoAPI>undo=[manager apiForProtocol:@protocol(FxUndoAPI)];
if([undo startUndoGroup:@"局部马赛克"]){DYWriteTools(manager,doc,a.currentTime);[undo endUndoGroup];}
}@finally{[a endAction:self];}
[_renderer invalidatePreview];[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:manager];
}
- (void)requestMosaicMenu {
dispatch_async(dispatch_get_main_queue(),^{
id manager=nil;@synchronized(self){if(!self->_invalidated)manager=self->_apiManager;}if(!manager)return;
id<FxCustomParameterActionAPI_v4>a=[manager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];[a startAction:self];NSDictionary *doc=nil;
@try{doc=[DYReadTools(manager,a.currentTime).document retain];}@finally{[a endAction:self];}
NSMenu *menu=[[[NSMenu alloc]initWithTitle:@"局部马赛克"]autorelease];NSDictionary *settings=doc[@"mosaic"];
auto add=[&](NSString *title,NSDictionary *value,BOOL checked){NSMenuItem *item=[menu addItemWithTitle:title action:@selector(applyMosaicMenu:) keyEquivalent:@""];item.target=self;item.representedObject=value;item.state=checked?NSControlStateValueOn:NSControlStateValueOff;};
add(@"应用到人脸(逐帧识别)",@{@"source":@"face",@"enabled":@YES},[settings[@"enabled"]boolValue]&&[settings[@"source"]isEqual:@"face"]);
NSInteger count=0;
for(NSDictionary *mask in DYSharedMasks(doc)){if(mask[@"stampSource"])continue;count++;DYMaskParameters p=DYMaskAtTime(mask,kCMTimeInvalid);NSString *shape=@[@"椭圆",@"矩形",@"钢笔",@"渐变",@"HSL",@"亮度"][p.kind];
add([NSString stringWithFormat:@"应用到蒙版 %ld · %@%@",(long)count,shape,[mask[@"keys"]count]?@" · 已跟踪":@""],@{@"source":@"mask",@"maskID":mask[@"id"],@"enabled":@YES},[settings[@"enabled"]boolValue]&&[settings[@"source"]isEqual:@"mask"]&&[settings[@"maskID"]isEqual:mask[@"id"]]);
}
if(!count){NSMenuItem *hint=[menu addItemWithTitle:@"先用矩形、椭圆或钢笔绘制蒙版" action:nil keyEquivalent:@""];hint.enabled=NO;}
[menu addItem:NSMenuItem.separatorItem];
for(NSNumber *size in @[@8,@16,@32,@64,@96,@128])add([NSString stringWithFormat:@"方块大小:%@",size],@{@"size":size},[settings[@"size"]isEqual:size]);
[menu addItem:NSMenuItem.separatorItem];add(@"关闭局部马赛克",@{@"enabled":@NO},![settings[@"enabled"]boolValue]);
[doc release];[menu popUpMenuPositioningItem:nil atLocation:NSEvent.mouseLocation inView:nil];
});
}
- (void)requestWorkspace{
[self requestWorkspacePage:@"tools"];
}