perf: defer unused GPU work and streamline preview rendering
这个提交包含在:
1 父节点
c9e4d3f330
当前提交
ccc34734e3
18 个文件已更改
+362
-115
没有与搜索条件相匹配的文件
@@ -35,7 +35,12 @@
|
||||
[handler release];[request release];_faceEntries=[[NSData alloc]initWithBytes:entries.data() length:entries.size()*sizeof(DYToolMaskEntry)];[_faceCachedEntries release];_faceCachedEntries=[_faceEntries copy];
|
||||
}
|
||||
- (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools error:(NSError**)error {@synchronized(self){
|
||||
DYUniforms effective=DYEffectiveFaceUniforms(u,paths,tools);BOOL face=effective.skinProtection.x>.5&&(effective.skinProtection.y>0||effective.skinVisualize>.5)&&(effective.skinFaceOnly>.5||effective.skinVisualize>.5);for(NSDictionary *node in tools[@"layers"]){DYUniforms layer=DYToolUniforms(node);face|=[node[@"type"]isEqual:@"skin"]&&!DYToolIsNeutral(node)&&layer.skinProtection.x>.5&&(layer.skinFaceOnly>.5||layer.skinVisualize>.5);}
|
||||
DYUniforms effective=DYEffectiveFaceUniforms(u,paths,tools);BOOL face=effective.skinProtection.x>.5&&(effective.skinProtection.y>0||effective.skinVisualize>.5)&&(effective.skinFaceOnly>.5||effective.skinVisualize>.5);for(NSDictionary *node in tools[@"layers"]){
|
||||
if(face)break;
|
||||
if(![node[@"type"]isEqual:@"skin"]||DYToolIsNeutral(node))continue;
|
||||
DYUniforms layer=DYToolUniforms(node);
|
||||
face=layer.skinProtection.x>.5&&(layer.skinFaceOnly>.5||layer.skinVisualize>.5);
|
||||
}
|
||||
if(face&&!_exporting)[self prepareFaceSupport:src];else{[_faceEntries release];_faceEntries=nil;}
|
||||
BOOL ok=[self renderToolsSource:src destination:dst uniforms:u paths:paths spider:spider tools:tools error:error];
|
||||
return ok;
|
||||
@@ -43,6 +48,7 @@
|
||||
- (BOOL)renderLens:(FxImageTile*)source destination:(FxImageTile*)destination uniforms:(DYUniforms)u masks:(NSArray*)masks entry:(NSDictionary*)entry error:(NSError**)error {
|
||||
if(source.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)u.lensCenterY=1-u.lensCenterY;
|
||||
id<MTLDevice>d=entry[@"device"];id<MTLTexture>before=[source metalTextureForDevice:d],output=[destination metalTextureForDevice:d];
|
||||
id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:entry[@"dyLensRepair"]];[ce setTexture:before atIndex:0];[ce setTexture:output atIndex:1];[ce setBytes:&u length:sizeof(u) atIndex:0];float aspect=before.width*source.pixelAspect/MAX(1.,(double)before.height);[ce setBytes:&aspect length:sizeof(aspect) atIndex:1];[ce dispatchThreads:MTLSizeMake(output.width,output.height,1)threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription);
|
||||
if(!masks.count)return YES;MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:output.pixelFormat width:output.width height:output.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite|MTLTextureUsageRenderTarget;id<MTLTexture>blend=[d newTextureWithDescriptor:desc];if(!blend)return fail(error,@"无法分配修复蒙版");DYToolMaskHeader h{};h.section=(int)[DYToolTypes()indexOfObject:@"lens"];id<MTLBuffer>buffer=[self maskBuffer:@{@"lens":masks}tile:source device:d header:&h];cb=[entry[@"queue"]commandBuffer];[self encodeBlend:before after:output output:blend masks:buffer header:h entry:entry commands:cb];[cb commit];[cb waitUntilCompleted];DYExportTile *tile=[[DYExportTile alloc]initWithTexture:blend registry:d.registryID];[tile setBounds:destination.tilePixelBounds origin:destination.imageOrigin];[tile setPixelAspect:destination.pixelAspect];BOOL ok=cb.status==MTLCommandBufferStatusCompleted&&[self copyTile:tile to:destination entry:entry error:error];[tile release];[blend release];return ok;
|
||||
id<MTLComputePipelineState> pipeline=[self computePipeline:@"dyLensRepair" entry:entry error:error];if(!pipeline)return NO;
|
||||
id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:pipeline];[ce setTexture:before atIndex:0];[ce setTexture:output atIndex:1];[ce setBytes:&u length:sizeof(u) atIndex:0];float aspect=before.width*source.pixelAspect/MAX(1.,(double)before.height);[ce setBytes:&aspect length:sizeof(aspect) atIndex:1];[ce dispatchThreads:MTLSizeMake(output.width,output.height,1)threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription);
|
||||
if(!masks.count)return YES;MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:output.pixelFormat width:output.width height:output.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite|MTLTextureUsageRenderTarget;id<MTLTexture>blend=[d newTextureWithDescriptor:desc];if(!blend)return fail(error,@"无法分配修复蒙版");DYToolMaskHeader h{};h.section=(int)[DYToolTypes()indexOfObject:@"lens"];id<MTLBuffer>buffer=[self maskBuffer:@{@"lens":masks}tile:source device:d header:&h];cb=[entry[@"queue"]commandBuffer];if(![self encodeBlend:before after:output output:blend masks:buffer header:h entry:entry commands:cb error:error]){[blend release];return NO;}[cb commit];[cb waitUntilCompleted];DYExportTile *tile=[[DYExportTile alloc]initWithTexture:blend registry:d.registryID];[tile setBounds:destination.tilePixelBounds origin:destination.imageOrigin];[tile setPixelAspect:destination.pixelAspect];BOOL ok=cb.status==MTLCommandBufferStatusCompleted&&[self copyTile:tile to:destination entry:entry error:error];[tile release];[blend release];return ok;
|
||||
}
|
||||
@@ -20,6 +20,14 @@
|
||||
ci=[[ci imageByApplyingFilter:@"CIGaussianBlur" withInputParameters:@{kCIInputRadiusKey:@(radius)}]imageByCroppingToRect:bounds];
|
||||
[context render:ci toMTLTexture:output commandBuffer:commands bounds:bounds colorSpace:nil];return YES;
|
||||
};
|
||||
NSMutableArray *needed=[NSMutableArray arrayWithObject:@"dyFilmPoint"];
|
||||
if(!mixer){
|
||||
if(DYFilmBloomActive(u.film))[needed addObjectsFromArray:@[@"dyFilmSparseBlur",@"dyFilmBloomEdges"]];
|
||||
if(DYFilmGrainActive(u.film))[needed addObject:@"dyFilmNoise"];
|
||||
if(DYFilmPrintActive(u))[needed addObject:@"dyFilmPrint"];
|
||||
if(u.film.mix<1)[needed addObject:@"dyFilmMix"];
|
||||
}
|
||||
for(NSString *name in needed)if(![self computePipeline:name entry:entry error:error])return NO;
|
||||
auto encode=[&](NSString *name,id<MTLTexture>a,id<MTLTexture>b,id<MTLTexture>out,const void *data,NSUInteger length){
|
||||
id<MTLComputeCommandEncoder>ce=[commands computeCommandEncoder];[ce setComputePipelineState:entry[name]];[ce setTexture:a atIndex:0];if(b)[ce setTexture:b atIndex:1];[ce setTexture:out atIndex:b?2:1];if(data)[ce setBytes:data length:length atIndex:0];[ce dispatchThreads:MTLSizeMake(out.width,out.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];
|
||||
};
|
||||
@@ -61,7 +69,7 @@
|
||||
}
|
||||
// Finish the effect before the module's existing mask blend. Source and
|
||||
// result retain identical alpha, and an empty mask group means full coverage.
|
||||
if(masks.count){id<MTLTexture>out=texture(current==slots[0]?1:0);if(!out)return fail(error,@"无法分配胶片蒙版缓冲区");DYToolMaskHeader header{};header.section=(int)[DYToolTypes()indexOfObject:type];id<MTLBuffer>buffer=[self maskBuffer:@{type:masks} tile:source device:d header:&header];[self encodeBlend:before after:current output:out masks:buffer header:header entry:entry commands:commands];current=out;}
|
||||
if(masks.count){id<MTLTexture>out=texture(current==slots[0]?1:0);if(!out)return fail(error,@"无法分配胶片蒙版缓冲区");DYToolMaskHeader header{};header.section=(int)[DYToolTypes()indexOfObject:type];id<MTLBuffer>buffer=[self maskBuffer:@{type:masks} tile:source device:d header:&header];if(![self encodeBlend:before after:current output:out masks:buffer header:header entry:entry commands:commands error:error])return NO;current=out;}
|
||||
[commands commit];[commands waitUntilCompleted];if(commands.status!=MTLCommandBufferStatusCompleted)return fail(error,commands.error.localizedDescription);
|
||||
DYExportTile *result=[[[DYExportTile alloc]initWithTexture:current registry:d.registryID]autorelease];[result setBounds:source.tilePixelBounds origin:source.imageOrigin];[result setPixelAspect:source.pixelAspect];return [self copyTile:result to:destination entry:entry error:error];
|
||||
}@catch(NSException *exception){return fail(error,[@"胶片处理失败:" stringByAppendingString:exception.reason?:@""]);}
|
||||
|
||||
+25
-8
@@ -232,16 +232,30 @@ fragment half4 dySegmentFragment(DYRaster in [[stage_in]],
|
||||
// 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.
|
||||
inline half4 dyStraightSample(float4 sample) {
|
||||
if (!(sample.a > 0.0f) || !all(isfinite(sample))) return half4(0.0h);
|
||||
return half4(half3(sample.rgb / sample.a), half(sample.a));
|
||||
}
|
||||
|
||||
kernel void dyUnpremultiply(texture2d<float, access::read> source [[texture(0)]],
|
||||
texture2d<half, access::write> destination [[texture(1)]],
|
||||
uint2 pixel [[thread_position_in_grid]]) {
|
||||
if (pixel.x >= destination.get_width() || pixel.y >= destination.get_height()) return;
|
||||
float4 sample = source.read(pixel);
|
||||
if (!(sample.a > 0.0f) || !all(isfinite(sample))) {
|
||||
destination.write(half4(0.0h), pixel);
|
||||
return;
|
||||
}
|
||||
destination.write(half4(half3(sample.rgb / sample.a), half(sample.a)), pixel);
|
||||
destination.write(dyStraightSample(source.read(pixel)), pixel);
|
||||
}
|
||||
|
||||
// Match the historical half-precision alpha round trip without an intermediate
|
||||
// texture when source and destination cover the same pixel grid.
|
||||
fragment half4 dyNeutralInputFragment(DYRaster in [[stage_in]],texture2d<float,access::read> source [[texture(0)]]) {
|
||||
uint2 size(source.get_width(),source.get_height());
|
||||
half4 c=dyStraightSample(source.read(min(uint2(in.uv*float2(size)),size-1)));
|
||||
return c.a>0.0h?half4(c.rgb*c.a,c.a):half4(0.0h);
|
||||
}
|
||||
|
||||
fragment half4 dyNeutralOutputFragment(DYRaster in [[stage_in]],texture2d<half> source [[texture(0)]]) {
|
||||
constexpr sampler f(coord::normalized,address::clamp_to_edge,filter::linear);
|
||||
half4 c=source.sample(f,in.uv);
|
||||
return c.a>0.0h?half4(c.rgb*c.a,c.a):half4(0.0h);
|
||||
}
|
||||
|
||||
// Per-instance CPU analysis thumbnail. Host dispatches exactly 64x64 threads;
|
||||
@@ -314,9 +328,12 @@ inline float3 dyDecode(float3 encoded) {
|
||||
}
|
||||
kernel void dyColorManagement(texture2d<float,access::read> source [[texture(0)]],
|
||||
texture2d<half,access::write> destination [[texture(1)]],
|
||||
constant DayuRenderParams& p [[buffer(0)]],constant float& amount [[buffer(1)]],uint2 pos [[thread_position_in_grid]]) {
|
||||
constant DayuRenderParams& p [[buffer(0)]],constant float& amount [[buffer(1)]],
|
||||
constant uint& premultiplied [[buffer(2)]],uint2 pos [[thread_position_in_grid]]) {
|
||||
if(pos.x>=source.get_width()||pos.y>=source.get_height())return;
|
||||
float4 sample=source.read(pos);if(!(sample.a>0)){destination.write(half4(0),pos);return;}
|
||||
float4 sample=source.read(pos);
|
||||
if(premultiplied)sample=float4(dyStraightSample(sample));
|
||||
if(!(sample.a>0)){destination.write(half4(0),pos);return;}
|
||||
float4 raw=float4(dyEncode(sample.rgb),sample.a),c=raw;
|
||||
if(p.stages&1)c=cst_air(half4(c),p.input);
|
||||
if(p.stages&2){if(p.reserved&8)c=cst_air(half4(c),p.basisInput);c=basis_air(half4(c),p.basis);if(p.reserved&8)c=cst_air(half4(c),p.basisOutput);}
|
||||
|
||||
@@ -23,3 +23,28 @@
|
||||
NSError *idleError=nil;BOOL idleOK=[probe renderSource:source destination:destination uniforms:fresh paths:@{} spider:nil tools:doc error:&idleError];
|
||||
run.record(@"idle-preview-empty-extra-skin-does-not-trigger-face-work",idleOK&&probe->faceCalls==3);
|
||||
}
|
||||
{
|
||||
DYRenderer *fast=[[[DYRenderer alloc]init]autorelease];
|
||||
DYUniforms untouched=defaults;untouched.primarySectionEnabled=0;
|
||||
Pixels wide=input;
|
||||
for(NSUInteger i=0;i<wide.size();i+=4){wide[i]*=-2;wide[i+1]*=4;}
|
||||
id<MTLTexture> texture=[source metalTextureForDevice:gpu];
|
||||
MTLRegion region=MTLRegionMake2D(0,0,width,height);
|
||||
[texture replaceRegion:region withBytes:wide.data() bytesPerRow:width*8];
|
||||
Pixels previewFrame=render(run,fast,source,destination,gpu,untouched,@{},@"neutral-preview-frame");
|
||||
NSError *fastError=nil;CMTime time=CMTimeMake(5,24);
|
||||
BOOL rendered=[fast renderHostSource:source destination:destination uniforms:untouched paths:@{} spider:nil tools:nil colorManagement:nil hostPrimaries:-1 atTime:time error:&fastError];
|
||||
Difference delta=difference(previewFrame,read(destination,gpu));
|
||||
BOOL direct=NO,lazy=YES;
|
||||
for(NSDictionary *entry in [[fast valueForKey:@"devices"]allValues]){
|
||||
for(NSString *key in entry[@"pipelines"])direct|=[key hasPrefix:@"dyNeutralInputFragment-"];
|
||||
lazy&=!entry[@"dyFilmNoise"]&&!entry[@"dyCloneStamps"]&&!entry[@"dyLensRepair"];
|
||||
}
|
||||
run.record(@"neutral-direct-preserves-hdr-negative-and-alpha",rendered&&direct&&delta.maximum==0&&delta.nonfinite==0,measure(delta));
|
||||
run.record(@"neutral-render-defers-unused-gpu-pipelines",lazy);
|
||||
DYScopeSample *sample=[[[fast valueForKey:@"scopeLatest"]retain]autorelease];
|
||||
run.record(@"final-scope-captured-with-neutral-output",[sample.metadata[@"timeValue"]integerValue]==5&&[sample.metadata[@"timeScale"]integerValue]==24&&sample.pixels.length==320*180*16);
|
||||
[fast captureScopeTile:destination atTime:time];
|
||||
run.record(@"final-scope-inline-matches-separate-capture",[sample.pixels isEqual:[[fast valueForKey:@"scopeLatest"]pixels]]);
|
||||
[texture replaceRegion:region withBytes:input.data() bytesPerRow:width*8];
|
||||
}
|
||||
+26
-18
@@ -975,7 +975,7 @@ NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing>
|
||||
id<FxCustomParameterActionAPI_v4> action=[self actionAPI]; if(!action)return;
|
||||
_refreshing=YES;
|
||||
uint64_t beta=DYBetaSpanBegin(@"inspector_refresh",nil);
|
||||
BOOL groupingChanged=NO;NSString *recentPath=nil;
|
||||
BOOL groupingChanged=NO;NSString *recentPath=nil;NSDictionary *stackDocument=nil;
|
||||
[action startAction:self];
|
||||
@try {
|
||||
CMTime t=action.currentTime;
|
||||
@@ -985,23 +985,31 @@ NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing>
|
||||
NSDictionary *cms=_embedded?DYReadAssets(maskHost,t).colorManagement:assets.colorManagement;
|
||||
NSDictionary *tools=DYReadTools(maskHost,t).document;
|
||||
DYInspectorToken *oldToken=nil;[get getCustomParameterValue:&oldToken fromParameter:DYInspectorParameterID atTime:t];
|
||||
BOOL wasUnified=_unified;
|
||||
_unified=DYUnifiedColorState(cms);
|
||||
groupingChanged=wasUnified!=_unified;
|
||||
if(!_embedded&&!_workspaceEditor){
|
||||
[_renderOrder release];_renderOrder=[DYUnifiedRenderOrder(tools)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;}
|
||||
if(!_renderOrder||groupingChanged){
|
||||
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;
|
||||
primary[@"body"]=body;
|
||||
}
|
||||
NSArray *order=DYUnifiedRenderOrder(tools);
|
||||
if(![_renderOrder isEqualToArray:order]){[_renderOrder release];_renderOrder=[order copy];}
|
||||
}
|
||||
NSDictionary *initialTools=tools;
|
||||
for(NSMutableDictionary *card in _cards){NSString *type=card[@"section"][@"key"];card[@"removed"]=@([type isEqual:@"output"]?!_unified:!_embedded&&DYBaseToolRemoved(initialTools,type));}
|
||||
NSMutableDictionary *graphicValues=[NSMutableDictionary dictionary];
|
||||
NSMutableDictionary *graphicValues=[NSMutableDictionary dictionary],*readValues=[NSMutableDictionary dictionary];
|
||||
auto readValue=[&](NSNumber *pid,double fallback){
|
||||
if(!pid)return fallback;
|
||||
NSNumber *cached=readValues[pid];if(cached)return cached.doubleValue;
|
||||
double value=fallback;[get getFloatValue:&value fromParameter:pid.unsignedIntValue atTime:t];
|
||||
if(!std::isfinite(value))value=fallback;
|
||||
readValues[pid]=@(value);return value;
|
||||
};
|
||||
for(NSNumber *pid in _controls) {
|
||||
NSDictionary *r=_controls[pid],*d=r[@"descriptor"]; double v=[d[@"default"] doubleValue];
|
||||
[get getFloatValue:&v fromParameter:pid.unsignedIntValue atTime:t];
|
||||
if(!std::isfinite(v))v=[d[@"default"] doubleValue];
|
||||
NSDictionary *r=_controls[pid],*d=r[@"descriptor"];double v=readValue(pid,[d[@"default"]doubleValue]);
|
||||
graphicValues[d[@"key"]]=@(v);
|
||||
if(d[@"enabled"]) {double enabled=1;[get getFloatValue:&enabled fromParameter:[d[@"enabled"] unsignedIntValue] atTime:t];[r[@"itemEnabled"] setState:enabled>=.5?NSControlStateValueOn:NSControlStateValueOff];[r[@"itemEnabled"] setImage:[NSImage imageWithSystemSymbolName:enabled>=.5?@"eye":@"eye.slash" accessibilityDescription:enabled>=.5?@"启用":@"旁路"]];for(NSString *control in @[@"slider",@"field",@"popup"]) [r[control] setAlphaValue:enabled>=.5?1:.45];}
|
||||
if(d[@"enabled"]) {double enabled=readValue(d[@"enabled"],1);[r[@"itemEnabled"] setState:enabled>=.5?NSControlStateValueOn:NSControlStateValueOff];[r[@"itemEnabled"] setImage:[NSImage imageWithSystemSymbolName:enabled>=.5?@"eye":@"eye.slash" accessibilityDescription:enabled>=.5?@"启用":@"旁路"]];for(NSString *control in @[@"slider",@"field",@"popup"]) [r[control] setAlphaValue:enabled>=.5?1:.45];}
|
||||
[r[@"slider"] setDoubleValue:v]; [r[@"field"] setStringValue:DYNumber(v,d)];
|
||||
[r[@"toggle"] setState:v>=.5?NSControlStateValueOn:NSControlStateValueOff];
|
||||
NSPopUpButton *popup=r[@"popup"]; if(popup.numberOfItems>0){NSArray *values=d[@"values"];NSInteger index=values?[values indexOfObject:@((int)llround(v))]:(NSInteger)llround(v);[popup selectItemAtIndex:index==NSNotFound?0:MAX(0,MIN(index,popup.numberOfItems-1))];}
|
||||
@@ -1010,9 +1018,8 @@ NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing>
|
||||
for(id graphic in _graphics)[graphic setValues:graphicValues];
|
||||
for(NSMutableDictionary *c in _cards) {
|
||||
NSNumber *pid=c[@"section"][@"enabled"];
|
||||
double v=[c[@"section"][@"defaultEnabled"]doubleValue];if(pid)[get getFloatValue:&v fromParameter:pid.unsignedIntValue atTime:t];
|
||||
NSNumber *extra=c[@"section"][@"extraEnabled"];double extraValue=0;
|
||||
if(extra)[get getFloatValue:&extraValue fromParameter:extra.unsignedIntValue atTime:t];
|
||||
double v=readValue(pid,[c[@"section"][@"defaultEnabled"]doubleValue]);
|
||||
double extraValue=readValue(c[@"section"][@"extraEnabled"],0);
|
||||
BOOL enabled=v>=.5||extraValue>=.5;
|
||||
NSNumber *saved=[oldToken isKindOfClass:DYInspectorToken.class]?oldToken.folds[c[@"section"][@"key"]]:nil;
|
||||
BOOL collapsed=_workspaceEditor?NO:saved?saved.boolValue:![self initiallyExpandedSection:c[@"section"][@"key"]];
|
||||
@@ -1036,24 +1043,25 @@ NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing>
|
||||
_tabs[@"managedColor"]=@(cms.count>0&&!DYPrimaryColorState(cms));_tabs[@"primaryCMS"]=@(DYPrimaryColorState(cms));[_managedPanel refreshWithState:assets.colorManagement context:[_renderer colorContext]];[_managedPanel setInputLUTPath:assets.paths[@"input"]];for(NSDictionary *r in _controls.allValues)if([r[@"descriptor"][@"key"]isEqual:@"cmmix"])[r[@"label"]setStringValue:([_tabs[@"managedColor"]boolValue]||[_tabs[@"primaryCMS"]boolValue])?@"调色混合":@"CST 混合"];
|
||||
for(NSDictionary *c in _cards)if([c[@"section"][@"key"]isEqual:@"primary"]){[c[@"enabled"]setToolTip:([_tabs[@"managedColor"]boolValue]||_unified)?@"启停此层一级调色;全局色彩管理保持当前方式":@"启停此层输入、一级调色与输出转换"];[c[@"enabled"]setAccessibilityHelp:[c[@"enabled"]toolTip]];}
|
||||
[_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];
|
||||
double profile=readValue(@2013,0),configured=readValue(@2236,0);
|
||||
_tabs[@"legacyInput"]=@(configured<.5&&(configured<0||profile>.5||[assets.paths[@"input"]length]||oldToken.schema<2));
|
||||
for(NSString *key in _assetButtons) {
|
||||
NSString *path=assets.paths[key]; NSButton *button=_assetButtons[key][@"choose"];
|
||||
NSString *name=path.length?path.lastPathComponent.stringByDeletingPathExtension:@"无";
|
||||
if([key isEqual:@"input"]&&!path.length){double profile=0;[get getFloatValue:&profile fromParameter:2013 atTime:t];for(NSDictionary *d in DYDescriptors())if([d[@"key"]isEqual:@"inputProfile"]){NSArray *options=d[@"options"];NSInteger index=MAX(0,MIN((NSInteger)llround(profile),(NSInteger)options.count-1));name=options[index];break;}}
|
||||
if([key isEqual:@"input"]&&!path.length){for(NSDictionary *d in DYDescriptors())if([d[@"key"]isEqual:@"inputProfile"]){NSArray *options=d[@"options"];NSInteger index=MAX(0,MIN((NSInteger)llround(profile),(NSInteger)options.count-1));name=options[index];break;}}
|
||||
button.title=_assetLoads[key]?@"正在载入…":name; button.toolTip=path.length?path:@"选择输入转换或 LUT;点击网格图标浏览缩略图";
|
||||
[_assetButtons[key][@"remove"] setEnabled:path.length>0];
|
||||
NSButton *eye=_assetButtons[key][@"eye"];if(eye){NSInteger slot=[[key substringFromIndex:4]integerValue];double enabled=1;[get getFloatValue:&enabled fromParameter:2040+(UInt32)slot-1 atTime:t];eye.state=enabled>=.5?NSControlStateValueOn:NSControlStateValueOff;eye.image=[NSImage imageWithSystemSymbolName:enabled>=.5?@"eye":@"eye.slash" accessibilityDescription:enabled>=.5?@"启用":@"旁路"];}
|
||||
NSButton *eye=_assetButtons[key][@"eye"];if(eye){NSInteger slot=[[key substringFromIndex:4]integerValue];double enabled=readValue(@(2040+(UInt32)slot-1),1);eye.state=enabled>=.5?NSControlStateValueOn:NSControlStateValueOff;eye.image=[NSImage imageWithSystemSymbolName:enabled>=.5?@"eye":@"eye.slash" accessibilityDescription:enabled>=.5?@"启用":@"旁路"];}
|
||||
}
|
||||
if(_recentBrowser)recentPath=[assets.paths[@"look0"]copy];
|
||||
for(NSInteger i=1;i<5;i++)if([assets.paths[[NSString stringWithFormat:@"look%ld",(long)i]]length])_visibleLooks=MAX(_visibleLooks,i+1);
|
||||
[self setNeedsLayout:YES];
|
||||
if(!_embedded&&!_workspaceEditor)stackDocument=[[tools copy]autorelease];
|
||||
} @finally { [action endAction:self]; _refreshing=NO; }
|
||||
[_recentBrowser refreshRecentSelection:recentPath];[recentPath release];
|
||||
// Remote layout/accessibility can re-enter the host. Let the parameter
|
||||
// action and current callback unwind before notifying the remote view.
|
||||
if(!_embedded&&!_workspaceEditor)[self synchronizeTools];
|
||||
if(stackDocument)[self synchronizeTools:stackDocument];
|
||||
DYBetaSpanEnd(beta,nil);
|
||||
if(groupingChanged)dispatch_async(dispatch_get_main_queue(),^{NSAccessibilityPostNotification(self,NSAccessibilityLayoutChangedNotification);});
|
||||
}
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
- (void)managedPreview:(id<MTLTexture>)texture origin:(FxImageOrigin)origin entry:(NSMutableDictionary*)entry {
|
||||
@synchronized(_previewLock){if(_exporting||CACurrentMediaTime()-_lastPreview<=.5)return;}
|
||||
id<MTLComputePipelineState>p=[self managedKernel:@"dyManagedPreview" entry:entry error:nil];if(!p)return;
|
||||
id<MTLComputePipelineState>p=[self computePipeline:@"dyManagedPreview" entry:entry error:nil];if(!p)return;
|
||||
id<MTLBuffer>b=[entry[@"device"]newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared];if(!b)return;
|
||||
id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:p];[ce setTexture:texture atIndex:0];[ce setBuffer:b offset:0 atIndex:0];[ce dispatchThreads:MTLSizeMake(320,180,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];
|
||||
if(cb.status==MTLCommandBufferStatusCompleted){@synchronized(_previewLock){[_preview release];_preview=[[NSData alloc]initWithBytes:b.contents length:b.length];[_lookLUTPreview release];if(origin==kFxImageOrigin_BOTTOM_LEFT){NSMutableData *flipped=[NSMutableData dataWithLength:b.length];for(NSUInteger y=0;y<180;y++)memcpy((uint8_t*)flipped.mutableBytes+y*320*16,(uint8_t*)b.contents+(179-y)*320*16,320*16);_lookLUTPreview=[flipped copy];}else _lookLUTPreview=[_preview retain];_lastPreview=CACurrentMediaTime();}dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:@"DYPreviewDidChange" object:self];});}[b release];
|
||||
}
|
||||
// Included in DYRenderer. V1 callers and their ABI remain on renderSource:...tools:error:.
|
||||
- (NSDictionary*)colorContext {@synchronized(_previewLock){return [[_colorContext copy]autorelease];}}
|
||||
- (id<MTLComputePipelineState>)managedKernel:(NSString*)name entry:(NSMutableDictionary*)entry error:(NSError**)error {
|
||||
NSMutableDictionary *cache=entry[@"managedKernels"];if(!cache){cache=[NSMutableDictionary dictionary];entry[@"managedKernels"]=cache;}
|
||||
id<MTLComputePipelineState>pipeline=cache[name];if(!pipeline){id<MTLFunction>f=[entry[@"library"]newFunctionWithName:name];if(!f){fail(error,[@"色彩管理内核缺失:" stringByAppendingString:name]);return nil;}pipeline=[entry[@"device"]newComputePipelineStateWithFunction:f error:error];[f release];if(!pipeline)return nil;cache[name]=pipeline;[pipeline release];}return pipeline;
|
||||
}
|
||||
- (BOOL)managedDispatch:(NSString*)name textures:(NSArray*)textures data:(const void*)data length:(NSUInteger)length extra:(const void*)extra extraLength:(NSUInteger)extraLength entry:(NSMutableDictionary*)entry error:(NSError**)error {
|
||||
id<MTLComputePipelineState>pipeline=[self managedKernel:name entry:entry error:error];if(!pipeline)return NO;
|
||||
id<MTLComputePipelineState>pipeline=[self computePipeline:name entry:entry error:error];if(!pipeline)return NO;
|
||||
id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:pipeline];for(NSUInteger i=0;i<textures.count;i++)[ce setTexture:textures[i] atIndex:i];if(data)[ce setBytes:data length:length atIndex:0];if(extra)[ce setBytes:extra length:extraLength atIndex:1];id<MTLTexture>t=textures[0];[ce dispatchThreads:MTLSizeMake(t.width,t.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];return cb.status==MTLCommandBufferStatusCompleted?YES:fail(error,cb.error.localizedDescription);
|
||||
}
|
||||
- (BOOL)managedConvert:(dycm::Space)from to:(dycm::Space)to display:(NSInteger)display gamut:(BOOL)gamut input:(id<MTLTexture>)input output:(id<MTLTexture>)output entry:(NSMutableDictionary*)entry error:(NSError**)error {
|
||||
@@ -44,7 +40,8 @@
|
||||
if(image.left!=bounds.left||image.right!=bounds.right||image.top!=bounds.top||image.bottom!=bounds.bottom){
|
||||
fail(error,@"仿制图章需要宿主提供完整的源画面。");return nil;
|
||||
}
|
||||
NSDictionary *entry=[self device:registry error:error];if(!entry)return nil;
|
||||
NSMutableDictionary *entry=[self device:registry error:error];if(!entry)return nil;
|
||||
id<MTLComputePipelineState> pipeline=[self computePipeline:@"dyCloneStamps" entry:entry error:error];if(!pipeline)return nil;
|
||||
id<MTLDevice>device=entry[@"device"];
|
||||
id<MTLTexture>input=[source metalTextureForDevice:device];
|
||||
if(!input||input.framebufferOnly){fail(error,@"仿制图章无法读取源画面。");return nil;}
|
||||
@@ -55,7 +52,7 @@
|
||||
id<MTLComputeCommandEncoder>encoder=[commands computeCommandEncoder];
|
||||
if(!output||!encoder){fail(error,@"无法分配仿制图章缓冲区。");return nil;}
|
||||
uint32_t count=(uint32_t)stamps.size(),flip=source.imageOrigin==kFxImageOrigin_BOTTOM_LEFT;
|
||||
[encoder setComputePipelineState:entry[@"dyCloneStamps"]];
|
||||
[encoder setComputePipelineState:pipeline];
|
||||
[encoder setTexture:input atIndex:0];[encoder setTexture:output atIndex:1];
|
||||
[encoder setBytes:stamps.data() length:count*sizeof(DYCloneStamp) atIndex:0];
|
||||
[encoder setBytes:&count length:sizeof(count) atIndex:1];[encoder setBytes:&flip length:sizeof(flip) atIndex:2];
|
||||
@@ -120,7 +117,7 @@
|
||||
auto convert=[&](dycm::Space a,dycm::Space b,NSInteger display=0,BOOL gamut=NO){id<MTLTexture>out=next();if(!out)return fail(error,@"无法分配色彩管理缓冲区。");BOOL ok=[self managedConvert:a to:b display:display gamut:gamut input:current output:out entry:entry error:error];if(ok)current=out;return ok;};
|
||||
auto profile=[&](DYColorProfile*p){id<MTLTexture>out=next();if(!out)return fail(error,@"无法分配颜色配置缓冲区。");BOOL ok=[self managedProfile:p input:current output:out entry:entry error:error];if(ok)current=out;return ok;};
|
||||
auto tile=[&](id<MTLTexture>texture){DYExportTile*t=[[[DYExportTile alloc]initWithTexture:texture registry:d.registryID]autorelease];[t setBounds:src.tilePixelBounds origin:src.imageOrigin];[t setPixelAspect:src.pixelAspect];return t;};
|
||||
auto blend=[&](id<MTLTexture>before,NSArray*masks,NSString*type){if(!masks.count)return YES;id<MTLTexture>out=next(before);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];id<MTLComputePipelineState>p=[self managedKernel:@"dyManagedBlend" entry:entry error:error];if(!mb||!p)return NO;id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:p];[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 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 blend=[&](id<MTLTexture>before,NSArray*masks,NSString*type){if(!masks.count)return YES;id<MTLTexture>out=next(before);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];id<MTLComputePipelineState>p=[self computePipeline:@"dyManagedBlend" entry:entry error:error];if(!mb||!p)return NO;id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:p];[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 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 basis=[&](DYUniforms values,NSArray*masks){values.cm.inputTransfer=values.cm.workingTransfer=values.cm.outputTransfer=1;values.cm.inputGamut=values.cm.workingGamut=values.cm.outputGamut=2;values.cm.toneMapping=0;values.inputSectionEnabled=values.cm.outputEnabled=0;if(values.primarySectionEnabled<.5||values.cm.basisEnabled<.5||identityCM(values)||values.cm.mix<=0)return YES;id<MTLTexture>before=current,out=next();BasisParams p=DYCMRender(values.cm).basis;float amount=values.cm.mix;if(!out||![self managedDispatch:@"dyManagedBasis" textures:@[current,out] data:&p length:sizeof(p) extra:&amount extraLength:4 entry:entry error:error])return NO;current=out;return blend(before,masks,@"primary");};
|
||||
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,out=next();float amount=values.filmPrint.y*values.film.mix;if(!out||![self managedDispatch:@"dyManagedPrint" textures:@[current,cube,out] data:&amount length:4 extra:nullptr extraLength:0 entry:entry error:error])return NO;current=out;return blend(before,masks,@"film");};
|
||||
@try{try{
|
||||
|
||||
@@ -52,7 +52,7 @@
|
||||
id<MTLBuffer>buffer=[self maskBuffer:face?@{}:@{@"primary":masks} tile:src device:device header:&header];_faceEntries=skinEntries;
|
||||
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];
|
||||
id<MTLComputePipelineState>pipeline=[self computePipeline:@"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.));
|
||||
|
||||
+35
-2
@@ -44,13 +44,46 @@
|
||||
if(!_modelRefreshPending.exchange(true)){id host=_apiManager;dispatch_async(dispatch_get_main_queue(),^{self->_modelRefreshPending.store(false);[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:host];});}return YES;}
|
||||
- (BOOL)pluginState:(NSData**)state atTime:(CMTime)t quality:(FxQuality)q error:(NSError**)e{
|
||||
uint64_t stateSpan=DYBetaSpanBegin(@"plugin_state",nil);@try{
|
||||
DYUniforms u;DYReadUniforms(_apiManager,t,&u);CMTime frameDuration=kCMTimeInvalid,origin=kCMTimeZero;id<FxTimingAPI_v4>timing=[_apiManager apiForProtocol:@protocol(FxTimingAPI_v4)];if([timing respondsToSelector:@selector(frameDuration:)])[timing frameDuration:&frameDuration];if([timing respondsToSelector:@selector(startTimeForEffect:)])[timing startTimeForEffect:&origin];int64_t frame=DYFilmFrameIndex(t,frameDuration,origin);u.filmFrameKey=DYFilmFrameKey(frame,u.film.grainHold,u.film.grainSeed);DYAssetState*a=DYReadAssets(_apiManager,t);DYToolDocument *tools=DYReadTools(_apiManager,t);[self adoptToolCanvasDocument:tools.document];[_viewerParameterBridge publishUniforms:&u document:tools.document atTime:t];[_viewerParameterBridge publishAssets:a atTime:t];double copyAuto=0;[[_apiManager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getFloatValue:©Auto fromParameter:8800 atTime:t];NSDictionary *snapshot=DYToolRenderSnapshot(tools.document,t);for(NSMutableDictionary *node in snapshot[@"layers"])if([node[@"type"]isEqual:@"film"]){DYUniforms layer=DYToolUniforms(node);node[@"filmFrameKey"]=@(DYFilmFrameKey(frame,layer.film.grainHold,layer.film.grainSeed));}NSInteger primaries=-1;id<FxColorGamutAPI_v2>gamut=[_apiManager apiForProtocol:@protocol(FxColorGamutAPI_v2)];if([gamut respondsToSelector:@selector(colorPrimaries)])primaries=gamut.colorPrimaries;NSDictionary*s=@{@"colorManagement":a.colorManagement?:@{},@"hostPrimaries":@(primaries),@"schema":@2,@"tools":snapshot,@"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 *assets=DYReadAssets(_apiManager,t);
|
||||
DYToolDocument *tools=DYReadTools(_apiManager,t);
|
||||
[self adoptToolCanvasDocument:tools.document];
|
||||
[_viewerParameterBridge publishUniforms:&u document:tools.document atTime:t];
|
||||
[_viewerParameterBridge publishAssets:assets atTime:t];
|
||||
double copyAuto=0;
|
||||
[[_apiManager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getFloatValue:©Auto fromParameter:8800 atTime:t];
|
||||
NSDictionary *snapshot=DYToolRenderSnapshot(tools.document,t);
|
||||
// Host timing is needed only for an active time-varying grain pass.
|
||||
BOOL hasFilmFrame=NO;
|
||||
int64_t frame=0;
|
||||
auto filmFrame=[&]{
|
||||
if(!hasFilmFrame){
|
||||
CMTime duration=kCMTimeInvalid,origin=kCMTimeZero;
|
||||
id<FxTimingAPI_v4> timing=[_apiManager apiForProtocol:@protocol(FxTimingAPI_v4)];
|
||||
if([timing respondsToSelector:@selector(frameDuration:)])[timing frameDuration:&duration];
|
||||
if([timing respondsToSelector:@selector(startTimeForEffect:)])[timing startTimeForEffect:&origin];
|
||||
frame=DYFilmFrameIndex(t,duration,origin);hasFilmFrame=YES;
|
||||
}
|
||||
return frame;
|
||||
};
|
||||
if(!DYBaseToolRemoved(snapshot,@"film")&&u.film.enabled>.5&&u.film.mix>0&&DYFilmGrainActive(u.film))
|
||||
u.filmFrameKey=DYFilmFrameKey(filmFrame(),u.film.grainHold,u.film.grainSeed);
|
||||
for(NSMutableDictionary *node in snapshot[@"layers"])if([node[@"type"]isEqual:@"film"]){
|
||||
DYFilmSettings film=DYToolUniforms(node).film;
|
||||
if(film.enabled>.5&&film.mix>0&&DYFilmGrainActive(film))node[@"filmFrameKey"]=@(DYFilmFrameKey(filmFrame(),film.grainHold,film.grainSeed));
|
||||
}
|
||||
NSInteger primaries=-1;
|
||||
id<FxColorGamutAPI_v2> gamut=[_apiManager apiForProtocol:@protocol(FxColorGamutAPI_v2)];
|
||||
if([gamut respondsToSelector:@selector(colorPrimaries)])primaries=gamut.colorPrimaries;
|
||||
NSDictionary *s=@{@"colorManagement":assets.colorManagement?:@{},@"hostPrimaries":@(primaries),@"schema":@2,@"tools":snapshot,@"copyAuto":@(copyAuto>.5),@"uniforms":[NSData dataWithBytes:&u length:sizeof(u)],@"paths":assets.paths?:@{},@"spider":assets.spiderMesh?:[NSData data]};
|
||||
*state=[NSPropertyListSerialization dataWithPropertyList:s format:NSPropertyListBinaryFormat_v1_0 options:0 error:e];
|
||||
return *state!=nil;
|
||||
}@finally{DYBetaSpanEnd(stateSpan,nil);}
|
||||
}
|
||||
- (BOOL)destinationImageRect:(FxRect*)rect sourceImages:(NSArray<FxImageTile*>*)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<FxImageTile*>*)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<FxImageTile*>*)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(![@[@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)];uint64_t renderSpan=DYBetaSpanBegin(@"render",@{@"width":@(src[0].ioSurface.width),@"height":@(src[0].ioSurface.height),@"layer_count":@([p[@"tools"][@"layers"]count])});uint64_t beta=!_betaFirstRenderStarted.exchange(true)?DYBetaSpanBegin(@"first_render",nil):0;BOOL ok=NO;@try{ok=[_renderer renderSource:src[0] destination:dst uniforms:u paths:p[@"paths"] spider:p[@"spider"] tools:p[@"tools"] colorManagement:p[@"colorManagement"] hostPrimaries:p[@"hostPrimaries"]?[p[@"hostPrimaries"]integerValue]:-1 error:e];}@finally{DYBetaSpanEnd(renderSpan,@{@"status":ok?@"passed":@"failed"});}DYBetaSpanEnd(beta,@{@"status":ok?@"passed":@"failed"});if(!ok)DYBetaEvent(@"render_error",DYBetaErrorFields((e&&*e)?*e:nil,@"render_source"));if(ok){[_renderer captureScopeTile:dst atTime:t];@synchronized(self){
|
||||
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)];uint64_t renderSpan=DYBetaSpanBegin(@"render",@{@"width":@(src[0].ioSurface.width),@"height":@(src[0].ioSurface.height),@"layer_count":@([p[@"tools"][@"layers"]count])});uint64_t beta=!_betaFirstRenderStarted.exchange(true)?DYBetaSpanBegin(@"first_render",nil):0;BOOL ok=NO;@try{ok=[_renderer renderHostSource:src[0] destination:dst uniforms:u paths:p[@"paths"] spider:p[@"spider"] tools:p[@"tools"] colorManagement:p[@"colorManagement"] hostPrimaries:p[@"hostPrimaries"]?[p[@"hostPrimaries"]integerValue]:-1 atTime:t error:e];}@finally{DYBetaSpanEnd(renderSpan,@{@"status":ok?@"passed":@"failed"});}DYBetaSpanEnd(beta,@{@"status":ok?@"passed":@"failed"});if(!ok)DYBetaEvent(@"render_error",DYBetaErrorFields((e&&*e)?*e:nil,@"render_source"));if(ok){@synchronized(self){
|
||||
FxRect image=src[0].imagePixelBounds;
|
||||
double aspect=src[0].pixelAspect,height=image.top-image.bottom,width=image.right-image.left;
|
||||
_toolSourceAspect=width>0&&height>0&&std::isfinite(aspect)&&aspect>0?width*aspect/height:0;
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
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 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 computePipeline:@"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};}
|
||||
|
||||
@@ -43,5 +43,6 @@
|
||||
- (NSDictionary *)scopeMetadata;
|
||||
- (NSDictionary*)colorContext;
|
||||
- (BOOL)renderSource:(FxImageTile*)source destination:(FxImageTile*)destination uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state hostPrimaries:(NSInteger)primaries error:(NSError**)error;
|
||||
- (BOOL)renderHostSource:(FxImageTile*)source destination:(FxImageTile*)destination uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state hostPrimaries:(NSInteger)primaries atTime:(CMTime)time error:(NSError**)error;
|
||||
- (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state error:(NSError**)error;
|
||||
@end
|
||||
+135
-29
@@ -70,13 +70,15 @@ static void bypassNeutralTools(DYUniforms *u){
|
||||
if(neutral)for(NSDictionary *row in DYDescriptors())if([row[@"pid"]isEqual:section[@"enabled"]])*(float*)((uint8_t*)u+[row[@"offset"]unsignedIntegerValue])=0;
|
||||
}
|
||||
}
|
||||
static BOOL hasLegacyGrade(const DYUniforms &u){
|
||||
if(u.curveSectionEnabled>.5||u.hslSectionEnabled>.5||u.colorGradingSectionEnabled>.5||u.primariesSectionEnabled>.5||u.levelsSectionEnabled>.5||u.blackWhiteSectionEnabled>.5||u.colorBalanceSectionEnabled>.5)return YES;
|
||||
if(u.preLUTStrength!=0||u.postLUTStrength!=0||simd_any(u.extraPostLUTStrengths!=0))return YES;
|
||||
const float *values=&u.exposure,*enabled=&u.exposureEnabled;
|
||||
for(int i=0;i<13;i++){BOOL group=(i>=6&&i<=9)?u.colorSectionEnabled>.5:u.baseSectionEnabled>.5;if(group&&enabled[i]>.5&&values[i]!=0)return YES;}
|
||||
return NO;
|
||||
}
|
||||
static void bypassIdleSkin(DYUniforms *u){
|
||||
if(u->skinVisualize>.5)return;
|
||||
if(u->curveSectionEnabled>.5||u->hslSectionEnabled>.5||u->colorGradingSectionEnabled>.5||u->primariesSectionEnabled>.5||u->levelsSectionEnabled>.5||u->blackWhiteSectionEnabled>.5||u->colorBalanceSectionEnabled>.5)return;
|
||||
if(u->preLUTStrength!=0||u->postLUTStrength!=0||simd_any(u->extraPostLUTStrengths!=0))return;
|
||||
const float *values=&u->exposure,*enabled=&u->exposureEnabled;
|
||||
for(int i=0;i<13;i++){BOOL group=(i>=6&&i<=9)?u->colorSectionEnabled>.5:u->baseSectionEnabled>.5;if(group&&enabled[i]>.5&&values[i]!=0)return;}
|
||||
u->skinProtection.x=0;
|
||||
if(u->skinVisualize<=.5&&!hasLegacyGrade(*u))u->skinProtection.x=0;
|
||||
}
|
||||
// Decide face work from the same effective operations that textures: and the
|
||||
// legacy renderer actually execute. Saved strengths remain 1 for empty LUT
|
||||
@@ -124,6 +126,11 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData
|
||||
NSDictionary*rootPaths=visiblePaths(paths,u);u=normalize(u);NSMutableDictionary*doc=DYMutablePlist(tools);for(NSMutableDictionary*node in doc[@"layers"]){DYUniforms original=DYToolUniforms(node),v=normalize(original);NSMutableDictionary*values=[NSMutableDictionary dictionary];for(NSDictionary*d in DYBaseToolDescriptors(node[@"type"]))if([d[@"offset"]integerValue]>=0)values[d[@"key"]]=@(*(float*)((uint8_t*)&v+[d[@"offset"]unsignedIntegerValue]));node[@"values"]=values;node[@"paths"]=visiblePaths(node[@"paths"],original);}
|
||||
return DYManagedActiveFinishing(u,rootPaths,spider,doc);
|
||||
}
|
||||
struct DYScopeReadback {
|
||||
id<MTLBuffer> buffer;
|
||||
NSUInteger generation;
|
||||
uint64_t serial;
|
||||
};
|
||||
@interface DYRenderer(){
|
||||
NSMutableDictionary *_devices,*_luts,*_preparedLUTs;
|
||||
NSSet *_activeLUTPaths;
|
||||
@@ -142,6 +149,9 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData
|
||||
NSUInteger _scopeGeneration;
|
||||
DYScopeSample *_scopePending,*_scopeLatest;
|
||||
uint64_t _scopeCaptureSerial,_scopeLatestSerial;CMTime _scopeRequestedTime;
|
||||
FxImageTile *_scopeDestination; // borrowed for one locked host render
|
||||
CMTime _scopeRenderTime;
|
||||
BOOL _scopeCaptured;
|
||||
NSData *_scopePreview;
|
||||
NSDictionary *_scopeMetadata;
|
||||
DYColorProfile *_scopeProfile;
|
||||
@@ -149,6 +159,22 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData
|
||||
}
|
||||
@end
|
||||
@implementation DYRenderer
|
||||
// The caller holds the renderer lock. Unused tools never load a GPU function.
|
||||
- (id<MTLComputePipelineState>)computePipeline:(NSString *)name entry:(NSMutableDictionary *)entry error:(NSError **)error {
|
||||
id<MTLComputePipelineState> pipeline=entry[name];
|
||||
if(pipeline)return pipeline;
|
||||
id<MTLLibrary> library=entry[@"library"];
|
||||
id<MTLDevice> device=entry[@"device"];
|
||||
id<MTLFunction> function=[library newFunctionWithName:name];
|
||||
if(!function){fail(error,[name stringByAppendingString:@" 缺失"]);return nil;}
|
||||
uint64_t span=DYBetaSpanBegin(@"gpu_pipeline",@{@"pipeline":name,@"gpu":device.name?:@"unknown"});
|
||||
pipeline=[device newComputePipelineStateWithFunction:function error:error];
|
||||
DYBetaSpanEnd(span,@{@"status":pipeline?@"passed":@"failed"});
|
||||
[function release];
|
||||
if(!pipeline)return nil;
|
||||
entry[name]=pipeline;
|
||||
return [pipeline autorelease];
|
||||
}
|
||||
#include "DYScopeCapture.inc.h"
|
||||
#include "DYFilmRender.inc.h"
|
||||
#include "DYPrimaryRender.inc.h"
|
||||
@@ -192,7 +218,6 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData
|
||||
NSURL*url=[[NSBundle bundleForClass:self.class]URLForResource:@"default" withExtension:@"metallib"];
|
||||
id<MTLLibrary>lib=[d newLibraryWithURL:url error:err];if(!lib){[d release];return nil;}
|
||||
id<MTLCommandQueue>q=[d newCommandQueue];entry=[NSMutableDictionary dictionaryWithDictionary:@{@"device":d,@"library":lib,@"queue":q,@"pipelines":[NSMutableDictionary dictionary]}];
|
||||
for(NSString*fn in @[@"dyLensRepair",@"dyUnpremultiply",@"dyWhitesSceneStatistics",@"dyLUTExportKernel",@"dyInputAnalysis",@"dyScopeSample",@"dyCloneStamps",@"dyColorManagement",@"dyToolBlend",@"dyToolSkin",@"dyFilmPoint",@"dyFilmNoise",@"dyFilmSparseBlur",@"dyFilmBloomEdges",@"dyFilmMix",@"dyFilmPrint"]){id<MTLFunction>f=[lib newFunctionWithName:fn];if(!f){fail(err,[fn stringByAppendingString:@" 缺失"]);[lib release];[q release];[d release];return nil;}uint64_t pipelineSpan=DYBetaSpanBegin(@"gpu_pipeline",@{@"pipeline":fn,@"gpu":d.name?:@"unknown"});id<MTLComputePipelineState>p=[d newComputePipelineStateWithFunction:f error:err];DYBetaSpanEnd(pipelineSpan,@{@"status":p?@"passed":@"failed"});[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;}id<MTLTexture>neutral=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.
|
||||
@@ -210,7 +235,7 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData
|
||||
- (NSArray*)textures:(NSDictionary*)paths uniforms:(DYUniforms*)u entry:(NSDictionary*)e error:(NSError**)err{
|
||||
// Normalize only this render copy. Disabled groups retain their host parameters
|
||||
// and paths, while inactive LUTs neither load files nor affect any layer.
|
||||
BOOL inputEnabled=u->inputSectionEnabled>.5&&!managed(*u,paths);
|
||||
BOOL inputEnabled=u->inputSectionEnabled>.5&&!managed(*u,paths)&&u->preLUTStrength>0;
|
||||
NSString*input=inputEnabled?paths[@"input"]:nil;int profile=inputEnabled?(int)roundf(u->inputProfile):0;
|
||||
if(!inputEnabled){u->inputProfile=0;u->preLUTStrength=0;}
|
||||
if(!input.length&&profile>0&&profile<(int)inputFiles().count)input=[[NSBundle bundleForClass:self.class]pathForResource:inputFiles()[profile] ofType:@"dylut" inDirectory:@"InputLUTs"];
|
||||
@@ -218,10 +243,20 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData
|
||||
NSMutableArray*ts=[NSMutableArray array];id<MTLTexture>t=[self lut:input entry:e error:err];if(!t)return nil;[ts addObject:t];if(!input.length)u->preLUTStrength=0;
|
||||
BOOL looksEnabled=u->lookSectionEnabled>.5;
|
||||
if(!looksEnabled)u->extraLookSectionEnableds=(DYFloat4){0,0,0,0};
|
||||
for(int i=0;i<5;i++){BOOL active=looksEnabled&&(i==0||u->extraLookSectionEnableds[i-1]>.5);NSString*p=active?paths[[NSString stringWithFormat:@"look%d",i]]:nil;t=[self lut:p entry:e error:err];if(!t)return nil;[ts addObject:t];if(!p.length){if(i==0)u->postLUTStrength=0;else u->extraPostLUTStrengths[i-1]=0;}}
|
||||
for(int i=0;i<5;i++){BOOL active=looksEnabled&&(i==0?u->postLUTStrength>0:u->extraLookSectionEnableds[i-1]>.5&&u->extraPostLUTStrengths[i-1]>0);NSString*p=active?paths[[NSString stringWithFormat:@"look%d",i]]:nil;t=[self lut:p entry:e error:err];if(!t)return nil;[ts addObject:t];if(!p.length){if(i==0)u->postLUTStrength=0;else u->extraPostLUTStrengths[i-1]=0;}}
|
||||
[DYColorTables fillPrimaries:u];id<MTLDevice>d=e[@"device"];
|
||||
id<MTLTexture>h=[_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)renderHostSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state hostPrimaries:(NSInteger)primaries atTime:(CMTime)time error:(NSError**)error {
|
||||
@synchronized(self){
|
||||
_scopeDestination=dst;_scopeRenderTime=time;_scopeCaptured=NO;
|
||||
@try{
|
||||
BOOL ok=[self renderSource:src destination:dst uniforms:u paths:paths spider:spider tools:tools colorManagement:state hostPrimaries:primaries error:error];
|
||||
if(ok&&!_scopeCaptured)[self captureScopeTile:dst atTime:time];
|
||||
return ok;
|
||||
}@finally{_scopeDestination=nil;}
|
||||
}
|
||||
}
|
||||
- (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{return [self renderSource:src destination:dst uniforms:u paths:paths spider:spider tools:nil error:err];}
|
||||
- (BOOL)renderLegacy:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData *)spider masks:(NSDictionary*)masks error:(NSError**)err{return [self renderLegacy:src destination:dst uniforms:u paths:paths spider:spider masks:masks stageFirst:-1 stageLast:-1 skinReference:nil originalReference:nil captureOriginal:nullptr suppressBlackWhite:NO error:err];}
|
||||
@@ -232,8 +267,9 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData
|
||||
|
||||
[_activeLUTPaths release];_activeLUTPaths=[[NSSet alloc]initWithArray:paths.allValues?:@[]];
|
||||
NSMutableDictionary*e=[self device:dst.deviceRegistryID error:err];if(!e)return NO;id<MTLDevice>d=e[@"device"];id<MTLTexture>input=[src metalTextureForDevice:d],output=[dst metalTextureForDevice:d];if(!input||!output)return fail(err,@"宿主图像纹理不可用");
|
||||
BOOL useCM=managed(u,paths)&&(!segmented||stageFirst==0);bypassNeutralTools(&u);float bwMix=fmaxf(0,fminf(1,u.cm.blackWhiteMix));if(bwMix<=0)u.blackWhiteSectionEnabled=0;
|
||||
NSArray*ts=[self textures:paths uniforms:&u entry:e error:err];if(!ts)return NO;bypassIdleSkin(&u);
|
||||
BOOL useCM=managed(u,paths)&&(!segmented||stageFirst==0)&&!identityCM(u)&&u.cm.mix>0;
|
||||
u=DYEffectiveFaceUniforms(u,paths,nil);
|
||||
float bwMix=u.blackWhiteSectionEnabled>.5?fmaxf(0,fminf(1,u.cm.blackWhiteMix)):0;
|
||||
// Only a deformed active mesh allocates samples; device entries retain the
|
||||
// current buffer across frames. Neutral grids are exact identity at all densities.
|
||||
simd_int2 spiderSize={0,0};id<MTLBuffer>spiderBuffer=nil;
|
||||
@@ -245,30 +281,100 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData
|
||||
}
|
||||
BOOL faceOnly=u.skinProtection.x>.5&&(u.skinProtection.y>0||u.skinVisualize>.5)&&u.skinFaceOnly>.5;
|
||||
DYToolMaskHeader maskHeader{};id<MTLBuffer>maskBuffer=(masks.count||segmented||faceOnly||_faceEntries.length)?[self maskBuffer:masks tile:src device:d header:&maskHeader]:nil;maskHeader.faceOnly=faceOnly;BOOL hasMasks=maskHeader.count>0||maskHeader.faceOnly;if((hasMasks||segmented)&&!maskBuffer)return fail(err,@"无法分配蒙版缓冲区");
|
||||
NSMutableDictionary*ps=e[@"pipelines"];NSString*format=[NSString stringWithFormat:@"%lu-%d-%d",(unsigned long)output.pixelFormat,hasMasks,segmented];id<MTLRenderPipelineState>pipeline=ps[format];if(!pipeline){MTLRenderPipelineDescriptor*p=[MTLRenderPipelineDescriptor new];p.vertexFunction=[e[@"library"]newFunctionWithName:@"dyVertex"];p.fragmentFunction=[e[@"library"]newFunctionWithName:segmented?@"dySegmentFragment":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;id<MTLTexture>straight=[d newTextureWithDescriptor:td];if(!straight)return fail(err,@"无法分配调色缓冲区");
|
||||
id<MTLCommandBuffer>cb=[e[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[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){id<MTLTexture>converted=[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];if(hasMasks){id<MTLTexture>blended=[d newTextureWithDescriptor:td];if(!blended){[converted release];[straight release];return fail(err,@"无法分配一级蒙版缓冲区");}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;
|
||||
BOOL preview=NO;
|
||||
@synchronized(_previewLock){preview=(!segmented||stageFirst==0)&&!_exporting&&CACurrentMediaTime()-_lastPreview>.5;}
|
||||
BOOL neutral=!segmented&&!hasMasks&&!spiderBuffer&&u.skinVisualize<.5&&!hasLegacyGrade(u);
|
||||
FxRect s=src.tilePixelBounds,t=dst.tilePixelBounds;
|
||||
BOOL sameGrid=input.width==output.width&&input.height==output.height&&s.left==t.left&&s.right==t.right&&s.top==t.top&&s.bottom==t.bottom;
|
||||
BOOL direct=neutral&&!useCM&&!preview&&sameGrid&&input!=output;
|
||||
NSString *fragment=direct?@"dyNeutralInputFragment":neutral?@"dyNeutralOutputFragment":segmented?@"dySegmentFragment":hasMasks?@"dyMaskedFragment":@"dyFragment";
|
||||
NSMutableDictionary *ps=e[@"pipelines"];
|
||||
NSString *format=[NSString stringWithFormat:@"%lu-%d-%d",(unsigned long)output.pixelFormat,hasMasks,segmented];
|
||||
if(neutral)format=[NSString stringWithFormat:@"%@-%lu",fragment,(unsigned long)output.pixelFormat];
|
||||
id<MTLRenderPipelineState> pipeline=ps[format];
|
||||
if(!pipeline){
|
||||
MTLRenderPipelineDescriptor *desc=[[[MTLRenderPipelineDescriptor alloc]init]autorelease];
|
||||
id<MTLLibrary> library=e[@"library"];
|
||||
desc.vertexFunction=[[library newFunctionWithName:@"dyVertex"]autorelease];
|
||||
desc.fragmentFunction=[[library newFunctionWithName:fragment]autorelease];
|
||||
desc.colorAttachments[0].pixelFormat=output.pixelFormat;
|
||||
pipeline=[[d newRenderPipelineStateWithDescriptor:desc error:err]autorelease];
|
||||
if(!pipeline)return NO;
|
||||
ps[format]=pipeline;
|
||||
}
|
||||
NSArray *ts=neutral?nil:[self textures:paths uniforms:&u entry:e error:err];
|
||||
if(!neutral&&!ts)return NO;
|
||||
id<MTLCommandBuffer> cb=[e[@"queue"]commandBuffer];
|
||||
id<MTLTexture> straight=input;
|
||||
if(!direct){
|
||||
MTLTextureDescriptor *td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:input.width height:input.height mipmapped:NO];
|
||||
td.storageMode=MTLStorageModePrivate;td.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;
|
||||
straight=segmented?nil:e[@"legacyStraight"];
|
||||
if(straight.width!=input.width||straight.height!=input.height){
|
||||
straight=[[d newTextureWithDescriptor:td]autorelease];
|
||||
if(straight&&!segmented)e[@"legacyStraight"]=straight;
|
||||
}
|
||||
if(!straight)return fail(err,@"无法分配调色缓冲区");
|
||||
MTLSize grid=MTLSizeMake(input.width,input.height,1),group=MTLSizeMake(16,16,1);
|
||||
BOOL fused=useCM&&!hasMasks;
|
||||
if(!fused){
|
||||
id<MTLComputePipelineState> unpremultiply=[self computePipeline:@"dyUnpremultiply" entry:e error:err];if(!unpremultiply)return NO;
|
||||
id<MTLComputeCommandEncoder> ce=[cb computeCommandEncoder];
|
||||
[ce setComputePipelineState:unpremultiply];[ce setTexture:input atIndex:0];[ce setTexture:straight atIndex:1];
|
||||
[ce dispatchThreads:grid threadsPerThreadgroup:group];[ce endEncoding];
|
||||
}
|
||||
if(useCM){
|
||||
DayuRenderParams cm=DYCMRender(u.cm);cm.stages=(cm.stages&~1)|(u.inputSectionEnabled>.5?1:0);
|
||||
id<MTLComputePipelineState> cst=[self computePipeline:@"dyColorManagement" entry:e error:err];if(!cst)return NO;
|
||||
id<MTLTexture> converted=fused?straight:[[d newTextureWithDescriptor:td]autorelease];
|
||||
if(!converted)return fail(err,@"无法分配 CST 缓冲区");
|
||||
uint32_t premultiplied=fused;
|
||||
id<MTLComputeCommandEncoder> ce=[cb computeCommandEncoder];
|
||||
[ce setComputePipelineState:cst];[ce setTexture:fused?input: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 setBytes:&premultiplied length:4 atIndex:2];
|
||||
[ce dispatchThreads:grid threadsPerThreadgroup:group];[ce endEncoding];
|
||||
if(hasMasks){
|
||||
id<MTLTexture> blended=[[d newTextureWithDescriptor:td]autorelease];if(!blended)return fail(err,@"无法分配一级蒙版缓冲区");
|
||||
maskHeader.section=0;maskHeader.premultiplied=0;
|
||||
if(![self encodeBlend:straight after:converted output:blended masks:maskBuffer header:maskHeader entry:e commands:cb error:err])return NO;
|
||||
converted=blended;
|
||||
}
|
||||
straight=converted;
|
||||
}
|
||||
}
|
||||
// Keep the actual post-CST straight source alive across all native segments.
|
||||
// Both native spatial helpers and whites statistics historically read this
|
||||
// source; the current segment's center color is a different input.
|
||||
id<MTLTexture>nativeSource=segmented&&originalReference?[originalReference metalTextureForDevice:d]:straight;
|
||||
if(!nativeSource){[straight release];return fail(err,@"原生工具参考纹理不可用");}
|
||||
// Segments retain the original straight source for spatial tools and statistics.
|
||||
id<MTLTexture> nativeSource=segmented&&originalReference?[originalReference metalTextureForDevice:d]:straight;
|
||||
if(!nativeSource)return fail(err,@"原生工具参考纹理不可用");
|
||||
if(segmented&&captureOriginal&&!*captureOriginal){DYExportTile *reference=[[DYExportTile alloc]initWithTexture:nativeSource registry:d.registryID];[reference setBounds:src.tilePixelBounds origin:src.imageOrigin];[reference setPixelAspect:src.pixelAspect];*captureOriginal=reference;}
|
||||
float level=.5;id<MTLBuffer>scene=[d newBufferWithBytes:&level length:4 options:MTLResourceStorageModeShared];
|
||||
if(!_exporting&&(!segmented||(stageFirst<=2&&stageLast>=2))&&u.whites>0&&u.whitesEnabled>.5&&u.baseSectionEnabled>.5){ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyWhitesSceneStatistics"]];[ce setTexture:nativeSource atIndex:0];[ce setTexture:ts[7] atIndex:1];[ce setBytes:&u length:sizeof(u) atIndex:0];[ce setBuffer:scene offset:0 atIndex:1];[ce dispatchThreadgroups:MTLSizeMake(1,1,1) threadsPerThreadgroup:MTLSizeMake(256,1,1)];[ce endEncoding];}
|
||||
BOOL preview=NO;@synchronized(_previewLock){preview=(!segmented||stageFirst==0)&&!_exporting&&CACurrentMediaTime()-_lastPreview>.5;}id<MTLBuffer>pb=nil;if(preview){pb=[d newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared];ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyInputAnalysis"]];[ce setTexture:straight atIndex:0];[ce setTexture:ts[0] atIndex:1];float inputStrength=u.inputSectionEnabled>.5?u.preLUTStrength:0;[ce setBytes:&inputStrength length:4 atIndex:1];[ce setBuffer:pb offset:0 atIndex:0];[ce dispatchThreads:MTLSizeMake(320,180,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[ce endEncoding];}
|
||||
id<MTLBuffer> scene=nil;
|
||||
if(!neutral){
|
||||
float level=.5;
|
||||
scene=[[d newBufferWithBytes:&level length:4 options:MTLResourceStorageModeShared]autorelease];
|
||||
if(!scene)return fail(err,@"无法分配调色统计缓冲区");
|
||||
if(!_exporting&&(!segmented||(stageFirst<=2&&stageLast>=2))&&u.whites>0&&u.whitesEnabled>.5&&u.baseSectionEnabled>.5){
|
||||
id<MTLComputePipelineState> stats=[self computePipeline:@"dyWhitesSceneStatistics" entry:e error:err];if(!stats)return NO;
|
||||
id<MTLComputeCommandEncoder> ce=[cb computeCommandEncoder];
|
||||
[ce setComputePipelineState:stats];[ce setTexture:nativeSource atIndex:0];[ce setTexture:ts[7] atIndex:1];[ce setBytes:&u length:sizeof(u) atIndex:0];[ce setBuffer:scene offset:0 atIndex:0];
|
||||
[ce dispatchThreadgroups:MTLSizeMake(1,1,1) threadsPerThreadgroup:MTLSizeMake(256,1,1)];[ce endEncoding];
|
||||
}
|
||||
}
|
||||
id<MTLBuffer> pb=nil;
|
||||
if(preview){
|
||||
id<MTLComputePipelineState> analysis=[self computePipeline:@"dyInputAnalysis" entry:e error:err];if(!analysis)return NO;
|
||||
pb=[[d newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared]autorelease];
|
||||
if(!pb)return fail(err,@"无法分配输入预览缓冲区");
|
||||
id<MTLComputeCommandEncoder> ce=[cb computeCommandEncoder];
|
||||
[ce setComputePipelineState:analysis];[ce setTexture:straight atIndex:0];[ce setTexture:neutral?e[@"identity"]:ts[0] atIndex:1];
|
||||
float inputStrength=u.inputSectionEnabled>.5?u.preLUTStrength:0;
|
||||
[ce setBytes:&inputStrength length:4 atIndex:1];[ce setBuffer:pb offset:0 atIndex:0];
|
||||
[ce dispatchThreads:MTLSizeMake(320,180,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[ce endEncoding];
|
||||
}
|
||||
MTLRenderPassDescriptor*rp=[MTLRenderPassDescriptor renderPassDescriptor];rp.colorAttachments[0].texture=output;rp.colorAttachments[0].loadAction=MTLLoadActionDontCare;rp.colorAttachments[0].storeAction=MTLStoreActionStore;id<MTLRenderCommandEncoder>re=[cb renderCommandEncoderWithDescriptor:rp];[re setRenderPipelineState:pipeline];
|
||||
float w=output.width,h=output.height;FxRect s=src.tilePixelBounds,t=dst.tilePixelBounds;float sw=s.right-s.left,sh=s.top-s.bottom;float l=(t.left-s.left)/sw,r=(t.right-s.left)/sw,top=(s.top-t.top)/sh,bottom=(s.top-t.bottom)/sh;
|
||||
float w=output.width,h=output.height;float sw=s.right-s.left,sh=s.top-s.bottom;float l=(t.left-s.left)/sw,r=(t.right-s.left)/sw,top=(s.top-t.top)/sh,bottom=(s.top-t.bottom)/sh;
|
||||
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;i<ts.count;i++)[re setFragmentTexture:ts[i] atIndex:i+1];[re setFragmentBytes:&u length:sizeof(u) atIndex:0];[re setFragmentBuffer:scene offset:0 atIndex:1];DYRenderOptions options={1,bwMix,0,0};[re setFragmentBytes:&options length:sizeof(options) atIndex:2];DYUniforms color=u;color.blackWhiteSectionEnabled=0;[re setFragmentBytes:&color length:sizeof(color) atIndex:3];if(spiderBuffer)[re setFragmentBuffer:spiderBuffer offset:0 atIndex:4];else{float empty[2]={0,0};[re setFragmentBytes:empty length:sizeof(empty) atIndex:4];}[re setFragmentBytes:&spiderSize length:sizeof(spiderSize) atIndex:5];if(hasMasks||segmented){[re setFragmentBuffer:maskBuffer offset:0 atIndex:6];[re setFragmentBytes:&maskHeader length:sizeof(maskHeader) atIndex:7];}if(segmented){DYToolStageRange range={(int)stageFirst,(int)stageLast,(int)suppressBlackWhite};[re setFragmentBytes:&range length:sizeof(range) atIndex:8];[re setFragmentTexture:skinReference?[skinReference metalTextureForDevice:d]:input atIndex:10];[re setFragmentTexture:nativeSource atIndex:11];}[re drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];[re endEncoding];[cb commit];[cb waitUntilCompleted];BOOL ok=cb.status==MTLCommandBufferStatusCompleted;
|
||||
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];if(!neutral){for(NSUInteger i=0;i<ts.count;i++)[re setFragmentTexture:ts[i] atIndex:i+1];[re setFragmentBytes:&u length:sizeof(u) atIndex:0];[re setFragmentBuffer:scene offset:0 atIndex:1];DYRenderOptions options={1,bwMix,0,0};[re setFragmentBytes:&options length:sizeof(options) atIndex:2];DYUniforms color=u;color.blackWhiteSectionEnabled=0;[re setFragmentBytes:&color length:sizeof(color) atIndex:3];if(spiderBuffer)[re setFragmentBuffer:spiderBuffer offset:0 atIndex:4];else{float empty[2]={0,0};[re setFragmentBytes:empty length:sizeof(empty) atIndex:4];}[re setFragmentBytes:&spiderSize length:sizeof(spiderSize) atIndex:5];if(hasMasks||segmented){[re setFragmentBuffer:maskBuffer offset:0 atIndex:6];[re setFragmentBytes:&maskHeader length:sizeof(maskHeader) atIndex:7];}if(segmented){DYToolStageRange range={(int)stageFirst,(int)stageLast,(int)suppressBlackWhite};[re setFragmentBytes:&range length:sizeof(range) atIndex:8];[re setFragmentTexture:skinReference?[skinReference metalTextureForDevice:d]:input atIndex:10];[re setFragmentTexture:nativeSource atIndex:11];}}[re drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];[re endEncoding];BOOL ok=[self completeCommands:cb destination:dst texture:output entry:e];
|
||||
if(ok&&pb){@synchronized(_previewLock){
|
||||
[_preview release];_preview=[[NSData alloc]initWithBytes:pb.contents length:320*180*16];
|
||||
// The analysis kernel reads physical texture rows. Its result remains intact
|
||||
@@ -281,7 +387,7 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData
|
||||
}else _lookLUTPreview=[_preview retain];
|
||||
_lastPreview=CACurrentMediaTime();[self notifyPreviewChanged];
|
||||
}}
|
||||
if(!ok)fail(err,cb.error.localizedDescription);[pb release];[straight release];[scene release];return ok;
|
||||
if(!ok)fail(err,cb.error.localizedDescription);return ok;
|
||||
});}}
|
||||
- (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)u paths:(NSDictionary*)paths error:(NSError**)err{return [self exportLUT:url uniforms:u paths:paths spider:nil error:err];}
|
||||
- (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider error:(NSError**)err{@synchronized(self){
|
||||
|
||||
+66
-27
@@ -80,37 +80,76 @@
|
||||
}});
|
||||
return raster;
|
||||
}
|
||||
- (void)captureScopeTile:(FxImageTile *)tile atTime:(CMTime)time{
|
||||
NSUInteger generation;uint64_t serial;@synchronized(_previewLock){if(_exporting||!tile)return;generation=_scopeGeneration;serial=++_scopeCaptureSerial;}
|
||||
@autoreleasepool{@try{
|
||||
NSDictionary *entry=nil,*context=nil;@synchronized(self){entry=[[self device:tile.deviceRegistryID error:nil]retain];context=[_colorContext copy];}
|
||||
id<MTLDevice>device=entry[@"device"];id<MTLTexture>texture=[tile metalTextureForDevice:device];
|
||||
if(!entry||!texture||!texture.width||!texture.height||texture.framebufferOnly){[entry release];[context release];return;}
|
||||
id<MTLBuffer>buffer=[device newBufferWithLength:dyscope::Width*dyscope::Height*sizeof(dyscope::RGBA) options:MTLResourceStorageModeShared];
|
||||
id<MTLCommandBuffer>command=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>encoder=[command computeCommandEncoder];
|
||||
if(!buffer||!encoder){[buffer release];[entry release];[context release];return;}
|
||||
uint32_t flip=tile.imageOrigin==kFxImageOrigin_BOTTOM_LEFT;[encoder setComputePipelineState:entry[@"dyScopeSample"]];[encoder setTexture:texture atIndex:0];[encoder setBuffer:buffer offset:0 atIndex:0];[encoder setBytes:&flip length:sizeof(flip) atIndex:1];
|
||||
[encoder dispatchThreads:MTLSizeMake(dyscope::Width,dyscope::Height,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[encoder endEncoding];[command commit];
|
||||
// The host may recycle its destination as soon as render returns. Complete
|
||||
// only this 320x180 readback while that ownership is still guaranteed.
|
||||
// CPU profile conversion, plotting and UI notification do not block render.
|
||||
[command waitUntilCompleted];
|
||||
if(command.status!=MTLCommandBufferStatusCompleted){[buffer release];[entry release];[context release];return;}
|
||||
DYScopeSample *sample=[DYScopeSample new];sample.pixels=[NSData dataWithBytes:buffer.contents length:buffer.length];sample.generation=generation;
|
||||
CGColorSpaceRef sourceSpace=DYManagedTileSpace(tile,[context[@"primaries"]integerValue]);sample.space=sourceSpace;if(sourceSpace)CGColorSpaceRelease(sourceSpace);
|
||||
FxRect bounds=tile.tilePixelBounds,image=tile.imagePixelBounds;BOOL whole=bounds.left==image.left&&bounds.right==image.right&&bounds.top==image.top&&bounds.bottom==image.bottom;
|
||||
sample.metadata=@{@"time":@(CMTimeGetSeconds(time)),@"timeValue":@(time.value),@"timeScale":@(time.timescale),@"timeEpoch":@(time.epoch),@"source":context[@"destination"]?:@"宿主 RGB",@"wholeImage":@(whole),@"region":whole?@"整帧取样":@"仅当前宿主输出分块",@"width":@(dyscope::Width),@"height":@(dyscope::Height)};
|
||||
[buffer release];[entry release];[context release];
|
||||
BOOL start=NO,notifyOutput=NO;@synchronized(_previewLock){
|
||||
if(serial>=_scopeLatestSerial){
|
||||
[_scopeLatest release];_scopeLatest=[sample retain];_scopeLatestSerial=serial;
|
||||
// The caller owns the destination until command completion. Only the small
|
||||
// result buffer is copied out of that lifetime, even when the scope is closed.
|
||||
- (DYScopeReadback)encodeScopeTile:(FxImageTile *)tile texture:(id<MTLTexture>)texture entry:(NSMutableDictionary *)entry commands:(id<MTLCommandBuffer>)command {
|
||||
if(_exporting||!tile||!texture.width||!texture.height||texture.framebufferOnly)return {};
|
||||
id<MTLComputePipelineState> pipeline=[self computePipeline:@"dyScopeSample" entry:entry error:nil];
|
||||
if(!pipeline)return {};
|
||||
id<MTLBuffer> buffer=entry[@"scopeBuffer"];
|
||||
if(!buffer){
|
||||
id<MTLDevice> device=entry[@"device"];
|
||||
buffer=[[device newBufferWithLength:dyscope::Width*dyscope::Height*sizeof(dyscope::RGBA) options:MTLResourceStorageModeShared]autorelease];
|
||||
if(!buffer)return {};
|
||||
entry[@"scopeBuffer"]=buffer;
|
||||
}
|
||||
id<MTLComputeCommandEncoder> encoder=[command computeCommandEncoder];
|
||||
if(!encoder)return {};
|
||||
uint32_t flip=tile.imageOrigin==kFxImageOrigin_BOTTOM_LEFT;
|
||||
[encoder setComputePipelineState:pipeline];[encoder setTexture:texture atIndex:0];
|
||||
[encoder setBuffer:buffer offset:0 atIndex:0];[encoder setBytes:&flip length:sizeof(flip) atIndex:1];
|
||||
[encoder dispatchThreads:MTLSizeMake(dyscope::Width,dyscope::Height,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];
|
||||
[encoder endEncoding];
|
||||
@synchronized(_previewLock){return {buffer,_scopeGeneration,++_scopeCaptureSerial};}
|
||||
}
|
||||
- (void)publishScopeReadback:(DYScopeReadback)readback tile:(FxImageTile *)tile atTime:(CMTime)time {
|
||||
if(!readback.buffer)return;
|
||||
@try{
|
||||
DYScopeSample *sample=[[[DYScopeSample alloc]init]autorelease];
|
||||
sample.pixels=[NSData dataWithBytes:readback.buffer.contents length:readback.buffer.length];
|
||||
sample.generation=readback.generation;
|
||||
CGColorSpaceRef space=DYManagedTileSpace(tile,[_colorContext[@"primaries"]integerValue]);
|
||||
sample.space=space;if(space)CGColorSpaceRelease(space);
|
||||
FxRect bounds=tile.tilePixelBounds,image=tile.imagePixelBounds;
|
||||
BOOL whole=bounds.left==image.left&&bounds.right==image.right&&bounds.top==image.top&&bounds.bottom==image.bottom;
|
||||
sample.metadata=@{@"time":@(CMTimeGetSeconds(time)),@"timeValue":@(time.value),@"timeScale":@(time.timescale),@"timeEpoch":@(time.epoch),@"source":_colorContext[@"destination"]?:@"宿主 RGB",@"wholeImage":@(whole),@"region":whole?@"整帧取样":@"仅当前宿主输出分块",@"width":@(dyscope::Width),@"height":@(dyscope::Height)};
|
||||
BOOL start=NO,notifyOutput=NO;
|
||||
@synchronized(_previewLock){
|
||||
if(readback.serial>=_scopeLatestSerial){
|
||||
[_scopeLatest release];_scopeLatest=[sample retain];_scopeLatestSerial=readback.serial;
|
||||
if(_outputObserved&&!_outputNotificationPending){_outputNotificationPending=YES;notifyOutput=YES;}
|
||||
}
|
||||
if(_scopeEnabled&&serial==_scopeLatestSerial&&(generation==_scopeGeneration||!CMTIME_IS_NUMERIC(_scopeRequestedTime)||CMTimeCompare(time,_scopeRequestedTime)==0)){sample.generation=_scopeGeneration;[_scopePending release];_scopePending=[sample retain];if(!_scopeWorkerRunning){_scopeWorkerRunning=YES;start=YES;}}
|
||||
}[sample release];
|
||||
if(_scopeEnabled&&readback.serial==_scopeLatestSerial&&(readback.generation==_scopeGeneration||!CMTIME_IS_NUMERIC(_scopeRequestedTime)||CMTimeCompare(time,_scopeRequestedTime)==0)){
|
||||
sample.generation=_scopeGeneration;[_scopePending release];_scopePending=[sample retain];
|
||||
if(!_scopeWorkerRunning){_scopeWorkerRunning=YES;start=YES;}
|
||||
}
|
||||
}
|
||||
if(notifyOutput)[self queueOutputNotification];
|
||||
if(start)dispatch_async(_scopeQueue,^{[self processPendingScopeSamples];});
|
||||
}@catch(NSException *exception){/* Scope diagnostics must never fail rendering. */}}
|
||||
}@catch(NSException *exception){/* Scope diagnostics must never fail rendering. */}
|
||||
}
|
||||
- (BOOL)completeCommands:(id<MTLCommandBuffer>)command destination:(FxImageTile *)destination texture:(id<MTLTexture>)texture entry:(NSMutableDictionary *)entry {
|
||||
DYScopeReadback readback{};
|
||||
if(destination==_scopeDestination){
|
||||
@try{readback=[self encodeScopeTile:destination texture:texture entry:entry commands:command];}
|
||||
@catch(NSException *exception){/* Fall back to separate sampling. */}
|
||||
}
|
||||
[command commit];[command waitUntilCompleted];
|
||||
if(command.status!=MTLCommandBufferStatusCompleted)return NO;
|
||||
if(readback.buffer){[self publishScopeReadback:readback tile:destination atTime:_scopeRenderTime];_scopeCaptured=YES;}
|
||||
return YES;
|
||||
}
|
||||
- (void)captureScopeTile:(FxImageTile *)tile atTime:(CMTime)time {
|
||||
@synchronized(self){@autoreleasepool{@try{
|
||||
if(!tile||_exporting)return;
|
||||
NSMutableDictionary *entry=[self device:tile.deviceRegistryID error:nil];
|
||||
id<MTLTexture> texture=[tile metalTextureForDevice:entry[@"device"]];
|
||||
id<MTLCommandBuffer> command=[entry[@"queue"]commandBuffer];
|
||||
DYScopeReadback readback=[self encodeScopeTile:tile texture:texture entry:entry commands:command];
|
||||
if(!readback.buffer)return;
|
||||
[command commit];[command waitUntilCompleted];
|
||||
if(command.status==MTLCommandBufferStatusCompleted)[self publishScopeReadback:readback tile:tile atTime:time];
|
||||
}@catch(NSException *exception){/* Scope diagnostics must never fail rendering. */}}}
|
||||
}
|
||||
- (void)processPendingScopeSamples{
|
||||
for(;;){@autoreleasepool{
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
- (void)synchronizeTools {
|
||||
id<FxCustomParameterActionAPI_v4>a=[self actionAPI];if(!a)return;[a startAction:self];NSDictionary *document=nil;@try{document=[DYReadTools(_manager,a.currentTime).document copy];}@finally{[a endAction:self];}
|
||||
- (void)synchronizeTools:(NSDictionary *)document {
|
||||
NSMutableArray *order=[NSMutableArray array];NSMutableDictionary *numbers=[NSMutableDictionary dictionary],*roots=[NSMutableDictionary dictionary];
|
||||
for(NSString *orderedID in DYToolDisplayOrder(document)){NSDictionary *node=DYToolWithID(document,orderedID);if(!node)continue;NSString *ID=node[@"id"],*type=node[@"type"];[order addObject:ID];roots[ID]=DYToolRootAnchor(document,ID)?:@"tail";NSInteger number=(numbers[type]?[numbers[type]integerValue]:(DYBaseToolRemoved(document,type)?0:1))+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];}
|
||||
DYInspector *view=_stackViews[ID];BOOL existed=view!=nil;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"];NSString *title=[NSString stringWithFormat:@"%@ %ld",section[@"title"],(long)number];[view->_cards[0][@"header"]setTitle:title];[view->_cards[0][@"removeButton"]setAccessibilityLabel:[title stringByAppendingString:@"删除此层"]];}
|
||||
[view refresh];[view setNeedsLayout:YES];
|
||||
if(existed)[view refresh];
|
||||
}
|
||||
for(NSString *ID in [[_stackViews.allKeys copy]autorelease])if(![order containsObject:ID]){[_stackViews[ID]removeFromSuperview];[_stackViews removeObjectForKey:ID];}
|
||||
[_stackOrder release];_stackOrder=[order copy];[_stackRoots release];_stackRoots=[roots copy];[document release];[self setNeedsLayout:YES];
|
||||
[_stackOrder release];_stackOrder=[order copy];[_stackRoots release];_stackRoots=[roots copy];[self setNeedsLayout:YES];
|
||||
}
|
||||
- (void)toolMask:(NSButton*)sender{if(sender.tag<0||sender.tag>=_cards.count)return;id host=_embedded?[(DYToolManager*)_manager host]:_manager;NSString *node=_embedded?[(DYToolManager*)_manager nodeID]:[@"base:" stringByAppendingString:_cards[sender.tag][@"section"][@"key"]];[NSNotificationCenter.defaultCenter postNotificationName:@"DYWorkspaceToolSelection" object:host userInfo:@{@"node":node,@"source":@"inspector"}];[(DYToolMaskPanel*)_cards[sender.tag][@"maskPanel"]addMenu:sender];}
|
||||
- (void)repeatTool:(NSButton*)sender{
|
||||
|
||||
@@ -9,8 +9,9 @@
|
||||
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);}
|
||||
}if(_faceEntries.length){const DYToolMaskEntry *faces=(const DYToolMaskEntry*)_faceEntries.bytes;entries.insert(entries.end(),faces,faces+_faceEntries.length/sizeof(DYToolMaskEntry));}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<MTLTexture>)before after:(id<MTLTexture>)after output:(id<MTLTexture>)output masks:(id<MTLBuffer>)masks header:(DYToolMaskHeader)h entry:(NSDictionary*)entry commands:(id<MTLCommandBuffer>)commands {
|
||||
id<MTLComputeCommandEncoder>encoder=[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)encodeBlend:(id<MTLTexture>)before after:(id<MTLTexture>)after output:(id<MTLTexture>)output masks:(id<MTLBuffer>)masks header:(DYToolMaskHeader)h entry:(NSMutableDictionary*)entry commands:(id<MTLCommandBuffer>)commands error:(NSError**)error {
|
||||
id<MTLComputePipelineState> pipeline=[self computePipeline:@"dyToolBlend" entry:entry error:error];if(!pipeline)return NO;
|
||||
id<MTLComputeCommandEncoder>encoder=[commands computeCommandEncoder];[encoder setComputePipelineState:pipeline];[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];return YES;
|
||||
}
|
||||
- (BOOL)copyTile:(FxImageTile*)source to:(FxImageTile*)dest entry:(NSMutableDictionary*)e error:(NSError**)error {
|
||||
return [self copyTile:source to:dest rotation:0 entry:e error:error];
|
||||
@@ -34,7 +35,7 @@
|
||||
if(source.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)vertex.textureCoordinate.y=1-vertex.textureCoordinate.y;
|
||||
if(dest.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)vertex.position.y=-vertex.position.y;
|
||||
}
|
||||
vector_uint2 size={(unsigned)b.width,(unsigned)b.height};id<MTLCommandBuffer>cb=[e[@"queue"]commandBuffer];MTLRenderPassDescriptor *pass=[MTLRenderPassDescriptor renderPassDescriptor];pass.colorAttachments[0].texture=b;pass.colorAttachments[0].loadAction=MTLLoadActionDontCare;pass.colorAttachments[0].storeAction=MTLStoreActionStore;id<MTLRenderCommandEncoder>encoder=[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);
|
||||
vector_uint2 size={(unsigned)b.width,(unsigned)b.height};id<MTLCommandBuffer>cb=[e[@"queue"]commandBuffer];MTLRenderPassDescriptor *pass=[MTLRenderPassDescriptor renderPassDescriptor];pass.colorAttachments[0].texture=b;pass.colorAttachments[0].loadAction=MTLLoadActionDontCare;pass.colorAttachments[0].storeAction=MTLStoreActionStore;id<MTLRenderCommandEncoder>encoder=[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];return [self completeCommands:cb destination:dest texture:b entry:e]?YES:fail(error,cb.error.localizedDescription);
|
||||
}
|
||||
// Extra skin keeps the source reference used by the prior release. All other
|
||||
// extra tools reuse the same isolated native tool path and their own mask group.
|
||||
@@ -50,10 +51,11 @@
|
||||
if([type isEqual:@"mixer"]||[type isEqual:@"film"]){layer.filmFrameKey=[node[@"filmFrameKey"]unsignedIntValue];return [self renderFilmTool:type source:source destination:destination uniforms:layer masks:node[@"masks"] entry:entry error:error];}
|
||||
if(![type isEqual:@"skin"])return [self renderLegacy:source destination:destination uniforms:layer paths:node[@"paths"] spider:node[@"spider"] masks:@{type:node[@"masks"]} error:error];
|
||||
id<MTLDevice>d=entry[@"device"];id<MTLTexture>before=[source metalTextureForDevice:d],input=[original metalTextureForDevice:d],after=[destination metalTextureForDevice:d];
|
||||
id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:entry[@"dyToolSkin"]];[ce setTexture:before atIndex:0];[ce setTexture:input atIndex:1];[ce setTexture:after atIndex:2];[ce setBytes:&layer length:sizeof(layer) atIndex:0];[ce dispatchThreads:MTLSizeMake(after.width,after.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription);
|
||||
id<MTLComputePipelineState> pipeline=[self computePipeline:@"dyToolSkin" entry:entry error:error];if(!pipeline)return NO;
|
||||
id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:pipeline];[ce setTexture:before atIndex:0];[ce setTexture:input atIndex:1];[ce setTexture:after atIndex:2];[ce setBytes:&layer length:sizeof(layer) atIndex:0];[ce dispatchThreads:MTLSizeMake(after.width,after.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]&&layer.skinFaceOnly<.5&&layer.skinVisualize<.5)return YES;
|
||||
MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:after.width height:after.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageRenderTarget|MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;id<MTLTexture>blend=[d newTextureWithDescriptor:desc];if(!blend)return fail(error,@"无法分配新增工具蒙版缓冲区");
|
||||
DYToolMaskHeader h{};h.section=3;h.faceOnly=layer.skinFaceOnly>.5;h.skinPreview=layer.skinProtection.x>.5&&layer.skinVisualize>.5;id<MTLBuffer>buffer=[self maskBuffer:@{type:node[@"masks"]} tile:source device:d header:&h];cb=[entry[@"queue"]commandBuffer];[self encodeBlend:before after:after output:blend masks:buffer header:h entry:entry commands:cb];[cb commit];[cb waitUntilCompleted];BOOL ok=cb.status==MTLCommandBufferStatusCompleted;
|
||||
DYToolMaskHeader h{};h.section=3;h.faceOnly=layer.skinFaceOnly>.5;h.skinPreview=layer.skinProtection.x>.5&&layer.skinVisualize>.5;id<MTLBuffer>buffer=[self maskBuffer:@{type:node[@"masks"]} tile:source device:d header:&h];cb=[entry[@"queue"]commandBuffer];if(![self encodeBlend:before after:after output:blend masks:buffer header:h entry:entry commands:cb error:error]){[blend release];return NO;}[cb commit];[cb waitUntilCompleted];BOOL ok=cb.status==MTLCommandBufferStatusCompleted;
|
||||
DYExportTile *blended=[[DYExportTile alloc]initWithTexture:blend registry:d.registryID];[blended setBounds:source.tilePixelBounds origin:source.imageOrigin];[blended setPixelAspect:source.pixelAspect];[blend release];if(ok)ok=[self copyTile:blended to:destination entry:entry error:error];else fail(error,cb.error.localizedDescription);[blended release];return ok;
|
||||
}
|
||||
- (BOOL)renderToolsSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools error:(NSError**)error {@synchronized(self){return DYRenderWithPool(error,[&]()->BOOL{
|
||||
@@ -99,7 +101,7 @@
|
||||
if(branch==0)bwTile=[tile retain];
|
||||
}
|
||||
DYExportTile *mixed=makeTile();if(!mixed)return fail(error,@"无法分配黑白混合缓冲区");DYToolMaskEntry constant{};constant.section=0;constant.combine=0;constant.mask.parameters=dyDefaultMaskParameters();constant.mask.parameters.kind=DYMaskRectangle;constant.mask.parameters.width=constant.mask.parameters.height=4000;constant.mask.parameters.feather=0;constant.mask.parameters.outputBlack=constant.mask.parameters.outputWhite=1;constant.mask.parameters.strength=bwMix;
|
||||
id<MTLBuffer>weight=[[d newBufferWithBytes:&constant length:sizeof(constant) options:MTLResourceStorageModeShared]autorelease];if(!weight){[mixed release];return fail(error,@"无法分配黑白混合权重");}DYToolMaskHeader h{};h.count=1;h.section=0;h.premultiplied=1;h.scaleX=h.scaleY=1;id<MTLCommandBuffer>commands=[entry[@"queue"]commandBuffer];[self encodeBlend:[tile metalTextureForDevice:d] after:[bwTile metalTextureForDevice:d] output:[mixed metalTextureForDevice:d] masks:weight header:h entry:entry commands:commands];[commands commit];[commands waitUntilCompleted];if(commands.status!=MTLCommandBufferStatusCompleted){[mixed release];return fail(error,commands.error.localizedDescription);}replace(mixed);
|
||||
id<MTLBuffer>weight=[[d newBufferWithBytes:&constant length:sizeof(constant) options:MTLResourceStorageModeShared]autorelease];if(!weight){[mixed release];return fail(error,@"无法分配黑白混合权重");}DYToolMaskHeader h{};h.count=1;h.section=0;h.premultiplied=1;h.scaleX=h.scaleY=1;id<MTLCommandBuffer>commands=[entry[@"queue"]commandBuffer];if(![self encodeBlend:[tile metalTextureForDevice:d] after:[bwTile metalTextureForDevice:d] output:[mixed metalTextureForDevice:d] masks:weight header:h entry:entry commands:commands error:error]){[mixed release];return NO;}[commands commit];[commands waitUntilCompleted];if(commands.status!=MTLCommandBufferStatusCompleted){[mixed release];return fail(error,commands.error.localizedDescription);}replace(mixed);
|
||||
}@finally{[prefix release];[bwTile release];}
|
||||
// An extra skin tool follows the original skin and B&W mixture once.
|
||||
if(!apply(@"base:skin"))return NO;
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
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];struct {CSTParams toLinear,fromLinear,originalTo709;float amount;}p={{wg,wt,2,20,0},{2,20,wg,wt,0},{initialGamut,initialTransfer,22,20,0},amount};id<MTLComputePipelineState>pipeline=[self managedKernel:@"dyUnifiedBlend" 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 setTexture:originalWorking?:before atIndex:3];[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 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];struct {CSTParams toLinear,fromLinear,originalTo709;float amount;}p={{wg,wt,2,20,0},{2,20,wg,wt,0},{initialGamut,initialTransfer,22,20,0},amount};id<MTLComputePipelineState>pipeline=[self computePipeline:@"dyUnifiedBlend" 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 setTexture:originalWorking?:before atIndex:3];[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};}
|
||||
|
||||
+2
-2
@@ -17,9 +17,9 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>XPC!</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.20.2</string>
|
||||
<string>1.21.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>113</string>
|
||||
<string>114</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string></string>
|
||||
<key>PlugInKit</key>
|
||||
|
||||
@@ -17,9 +17,9 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.20.2</string>
|
||||
<string>1.21.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>113</string>
|
||||
<string>114</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
|
||||
更新于 2026-11-08(Asia/Shanghai)。这是新对话的接手入口。历史设计和实现细节按需查阅专项交接,复现和交付证据以对应版本的报告为准。
|
||||
|
||||
## 1.21.0(114)流畅性优化
|
||||
|
||||
按首帧、连续渲染和检查器刷新优化。Metal 管线首次使用才创建,中性画面跳过通用调色与查找纹理,保留原来的半精度透明度规则;无蒙版 CST 将解除预乘并入原转换内核。最终画面取样合并进输出命令并复用小缓冲,仍保留暂停帧的示波器样本。检查器复用本轮的宿主读参和工具文档,只在切换色彩管理模式时移动输出控件。胶片颗粒未参与时省去宿主帧时序查询。
|
||||
|
||||
入口为 `DYRenderer.mm`、`DYGrade.metal`、`DYScopeCapture.inc.h`、`DYPlugIn.mm` 与 `DYInspector.mm`。正在进行像素回归、正式构建和宿主验收。此检查点的正式安装仍是 1.20.2(113)。接手先核对构建与回归状态,再完成 APP、PKG 与 Release 验证。
|
||||
|
||||
## 2026-11-08 默认参数渲染排查
|
||||
|
||||
核对正式安装 1.20.2(113)、编译提交 `046411ba8b2c2bf8549601b2e5a080fd9dccd31b`。整合版、HSL、一级调色和 CST 独立效果的已安装模板、APP 内置模板和源码逐字节一致。整合模板没有额外工具层、LUT 或变形网格,默认执行 Sony S-Log3 / S-Gamut3.Cine 到 Gamma 2.4 / Rec.709 的 CST,自动色调映射开启。独立 HSL 的工具文档移除了一级调色。
|
||||
|
||||
在新工单中引用
屏蔽一个用户