// Included in DYRenderer; all calls execute under its per-instance recursive lock. - (id)maskBuffer:(NSDictionary*)groups tile:(FxImageTile*)tile device:(id)device header:(DYToolMaskHeader*)h { std::vector entries;FxRect image=tile.imagePixelBounds,bounds=tile.tilePixelBounds; float w=image.right-image.left,ht=image.top-image.bottom;BOOL bottom=tile.imageOrigin==kFxImageOrigin_BOTTOM_LEFT; h->offsetX=(bounds.left-image.left)/w;h->scaleX=(bounds.right-bounds.left)/w; h->offsetY=bottom?(image.top-bounds.bottom)/ht:(image.top-bounds.top)/ht;h->scaleY=(bottom?-1:1)*(bounds.top-bounds.bottom)/ht; h->premultiplied=1; for(NSString *type in groups){NSInteger section=[DYToolTypes()indexOfObject:type];if(section==NSNotFound)continue; for(NSDictionary *m in groups[type]){if(![m[@"enabled"]boolValue])continue;DYToolMaskEntry entry{};entry.section=(int)section;entry.combine=[m[@"combine"]intValue];[m[@"parameters"]getBytes:&entry.mask.parameters length:sizeof(DYMaskParameters)];entry.mask.parameters.imageAspect=w/ht;NSData *nodes=m[@"nodes"];entry.mask.path=dyFlattenMask((const DYBezierNode*)nodes.bytes,nodes.length/sizeof(DYBezierNode));entries.push_back(entry);} }h->count=(unsigned)entries.size();if(entries.empty())entries.push_back({});return [[device newBufferWithBytes:entries.data() length:entries.size()*sizeof(DYToolMaskEntry) options:MTLResourceStorageModeShared]autorelease]; } - (void)encodeBlend:(id)before after:(id)after output:(id)output masks:(id)masks header:(DYToolMaskHeader)h entry:(NSDictionary*)entry commands:(id)commands { idencoder=[commands computeCommandEncoder];[encoder setComputePipelineState:entry[@"dyToolBlend"]];[encoder setTexture:before atIndex:0];[encoder setTexture:after atIndex:1];[encoder setTexture:output atIndex:2];[encoder setBuffer:masks offset:0 atIndex:0];[encoder setBytes:&h length:sizeof(h) atIndex:1];[encoder dispatchThreads:MTLSizeMake(output.width,output.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[encoder endEncoding]; } - (BOOL)copyTile:(FxImageTile*)source to:(FxImageTile*)dest entry:(NSMutableDictionary*)e error:(NSError**)error { iddevice=e[@"device"];ida=[source metalTextureForDevice:device],b=[dest metalTextureForDevice:device]; NSMutableDictionary *pipelines=e[@"pipelines"];NSString *key=[NSString stringWithFormat:@"copy-%lu",(unsigned long)b.pixelFormat];idpipeline=pipelines[key]; if(!pipeline){MTLRenderPipelineDescriptor *desc=[MTLRenderPipelineDescriptor new];desc.vertexFunction=[e[@"library"]newFunctionWithName:@"dyVertex"];desc.fragmentFunction=[e[@"library"]newFunctionWithName:@"dyToolCopyFragment"];desc.colorAttachments[0].pixelFormat=b.pixelFormat;pipeline=[device newRenderPipelineStateWithDescriptor:desc error:error];[desc.vertexFunction release];[desc.fragmentFunction release];[desc release];if(!pipeline)return NO;pipelines[key]=pipeline;[pipeline release];} FxRect s=source.tilePixelBounds,t=dest.tilePixelBounds;float width=s.right-s.left,height=s.top-s.bottom,l=(t.left-s.left)/width,r=(t.right-s.left)/width,top=(s.top-t.top)/height,bottom=(s.top-t.bottom)/height; if(source.imageOrigin==kFxImageOrigin_BOTTOM_LEFT){top=1-top;bottom=1-bottom;} float w=b.width,h=b.height;DYVertex2D v[]={{{w/2,-h/2},{r,bottom}},{{-w/2,-h/2},{l,bottom}},{{w/2,h/2},{r,top}},{{-w/2,h/2},{l,top}}};if(dest.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)for(auto &vertex:v)vertex.position.y=-vertex.position.y; vector_uint2 size={(unsigned)b.width,(unsigned)b.height};idcb=[e[@"queue"]commandBuffer];MTLRenderPassDescriptor *pass=[MTLRenderPassDescriptor renderPassDescriptor];pass.colorAttachments[0].texture=b;pass.colorAttachments[0].loadAction=MTLLoadActionDontCare;pass.colorAttachments[0].storeAction=MTLStoreActionStore;idencoder=[cb renderCommandEncoderWithDescriptor:pass];[encoder setRenderPipelineState:pipeline];[encoder setVertexBytes:v length:sizeof(v) atIndex:0];[encoder setVertexBytes:&size length:sizeof(size) atIndex:1];[encoder setFragmentTexture:a atIndex:0];[encoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];[encoder endEncoding];[cb commit];[cb waitUntilCompleted];return cb.status==MTLCommandBufferStatusCompleted?YES:fail(error,cb.error.localizedDescription); } // 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. - (BOOL)renderExtraTool:(NSDictionary*)node source:(FxImageTile*)source original:(FxImageTile*)original destination:(FxImageTile*)destination entry:(NSMutableDictionary*)entry error:(NSError**)error { // Prove a constant-zero aggregate conservatively. In particular a first // subtract mask of strength zero is full coverage, not an empty selection. // Skipping only this isolated operation preserves HDR/negative pixels that // the legacy grading entry would otherwise clip even at zero stage coverage. BOOL found=NO;float low=1,high=1;for(NSDictionary *mask in node[@"masks"]){if(![mask[@"enabled"]boolValue])continue;DYMaskParameters p=DYMaskAtTime(mask,kCMTimeInvalid);float a=0,b=p.strength==0?0:1;NSInteger combine=[mask[@"combine"]integerValue];if(!found){low=combine==1?1-b:a;high=combine==1?1-a:b;found=YES;}else if(combine==1){low*=1-b;high*=1-a;}else if(combine==2){low*=a;high*=b;}else{low=1-(1-low)*(1-a);high=1-(1-high)*(1-b);}} if(found&&high==0)return [self copyTile:source to:destination entry:entry error:error]; DYUniforms layer=DYToolUniforms(node);NSString *type=node[@"type"]; 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]; idd=entry[@"device"];idbefore=[source metalTextureForDevice:d],input=[original metalTextureForDevice:d],after=[destination metalTextureForDevice:d]; idcb=[entry[@"queue"]commandBuffer];idce=[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); if(![node[@"masks"]count])return YES; MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:after.width height:after.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageRenderTarget|MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;idblend=[d newTextureWithDescriptor:desc];if(!blend)return fail(error,@"无法分配新增工具蒙版缓冲区"); DYToolMaskHeader h{};h.section=3;idbuffer=[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; 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)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools error:(NSError**)error {@synchronized(self){@autoreleasepool{ if(!tools)tools=@{@"schema":@1,@"layers":@[],@"baseMasks":@{}};if(!DYValidToolDocument(tools))return fail(error,@"工具或蒙版数据损坏,未更改原工程"); NSArray *layers=tools[@"layers"];BOOL active=NO,anchored=NO;for(NSDictionary *node in layers)if(!DYToolIsNeutral(node)){active=YES;anchored|=![DYToolRootAnchor(tools,node[@"id"])isEqual:@"tail"];} // No active extra tool keeps the exact historical fused path, including HDR. if(!active&&!DYChannelMixerActive(u)&&!DYFilmToolActive(u))return [self renderLegacy:src destination:dst uniforms:u paths:paths spider:spider masks:tools[@"baseMasks"] error:error]; NSMutableDictionary *entry=[self device:dst.deviceRegistryID error:error];if(!entry)return NO;idd=entry[@"device"];idinput=[src metalTextureForDevice:d];if(!input)return fail(error,@"宿主图像纹理不可用"); MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:input.width height:input.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageRenderTarget|MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite; DYExportTile *tile=nil,*skinReference=nil,*originalReference=nil;NSArray *order=DYToolDisplayOrder(tools);NSMutableDictionary *groups=[NSMutableDictionary dictionary];for(NSString *ID in order){NSDictionary *node=DYToolWithID(tools,ID);if(!node||DYToolIsNeutral(node))continue;NSString *root=DYToolRootAnchor(tools,ID);if(!groups[root])groups[root]=[NSMutableArray array];[groups[root]addObject:node];} auto makeTile=[&](){idtexture=[d newTextureWithDescriptor:desc];if(!texture)return (DYExportTile*)nil;DYExportTile *result=[[DYExportTile alloc]initWithTexture:texture registry:d.registryID];[result setBounds:src.tilePixelBounds origin:src.imageOrigin];[result setPixelAspect:src.pixelAspect];[texture release];return result;}; auto replace=[&](DYExportTile *next){[tile release];tile=next;}; auto apply=[&](NSString *anchor){for(NSDictionary *node in groups[anchor]){@autoreleasepool{DYExportTile *next=makeTile();if(!next)return fail(error,@"无法分配新增工具缓冲区");BOOL ok=[self renderExtraTool:node source:tile original:src destination:next entry:entry error:error];if(!ok){[next release];return NO;}replace(next);}}return YES;}; @try{ if(!anchored){DYExportTile *next=makeTile();if(!next)return fail(error,@"无法分配工具图层缓冲区");BOOL ok=[self renderLegacy:src destination:next uniforms:u paths:paths spider:spider masks:tools[@"baseMasks"] error:error];if(!ok){[next release];return NO;}replace(next);} else { // Preserve the actual native stage order, which predates the visual cards. // Basic adjustment spans stages 2/8, so its insertion point is after stage 8. // CST precedes stage 0; Spider stays after all twelve fused color stages. NSArray *anchors=@[@"base:primary",@"base:primaries",@"",@"base:curve",@"base:levels",@"base:balance",@"base:hsl",@"base:grading",@"base:base",@"base:blackwhite",@"base:look",@"base:skin"]; float bwMix=fmaxf(0,fminf(1,u.cm.blackWhiteMix));BOOL splitBW=u.blackWhiteSectionEnabled>.5&&bwMix>0&&bwMix<1&&([groups[@"base:blackwhite"]count]||[groups[@"base:look"]count]); NSInteger first=0; for(NSInteger last=0;last<(splitBW?9:12);last++)if(last==5||last==(splitBW?8:11)||[groups[anchors[last]]count]){@autoreleasepool{ DYExportTile *next=makeTile();if(!next)return fail(error,@"无法分配原生工具分段缓冲区");DYUniforms segment=u; BOOL ok=[self renderLegacy:tile?:src destination:next uniforms:segment paths:paths spider:nil masks:tools[@"baseMasks"] stageFirst:first stageLast:last skinReference:skinReference originalReference:originalReference captureOriginal:first==0?&originalReference:nullptr suppressBlackWhite:NO error:error];if(!ok){[next release];return NO;}replace(next); if(!apply(anchors[last]))return NO; // Skin protects the native pre-HSL result, including tools inserted before it. if(last==5){[skinReference release];skinReference=[tile retain];}first=last+1; }} if(splitBW){ // Native partial B&W mixes two complete color branches after native skin, // before Spider. Keep that fork if a B&W/Look insertion splits stages 9-11. // Only the suffix is duplicated; CST, statistics and the prefix stay shared. DYExportTile *prefix=[tile retain],*bwTile=nil; @try{ for(int branch=0;branch<2;branch++){ if(branch==1)replace([prefix retain]);DYUniforms branchUniforms=u;branchUniforms.cm.blackWhiteMix=1;NSInteger begin=9; for(NSInteger end=9;end<12;end++)if(end==11||[groups[anchors[end]]count]){@autoreleasepool{ DYExportTile *next=makeTile();if(!next)return fail(error,@"无法分配黑白混合分支缓冲区");BOOL ok=[self renderLegacy:tile destination:next uniforms:branchUniforms paths:paths spider:nil masks:tools[@"baseMasks"] stageFirst:begin stageLast:end skinReference:skinReference originalReference:originalReference captureOriginal:nullptr suppressBlackWhite:branch==1 error:error];if(!ok){[next release];return NO;}replace(next);if(end<11&&!apply(anchors[end]))return NO;begin=end+1; }} 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; idweight=[[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;idcommands=[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); }@finally{[prefix release];[bwTile release];} // An extra skin tool follows the original skin and B&W mixture once. if(!apply(@"base:skin"))return NO; } if(u.spiderSectionEnabled>.5&&u.spiderMix>0&&spider.length){DYUniforms sp=DYToolUniforms(@{@"type":@"spider"});sp.spiderSectionEnabled=u.spiderSectionEnabled;sp.spiderMix=u.spiderMix;DYExportTile *next=makeTile();if(!next)return fail(error,@"无法分配蜘蛛盘缓冲区");BOOL ok=[self renderLegacy:tile destination:next uniforms:sp paths:@{} spider:spider masks:@{@"spider":tools[@"baseMasks"][@"spider"]?:@[]} error:error];if(!ok){[next release];return NO;}replace(next);} if(!apply(@"base:spider"))return NO; } // New end-of-chain base tools do not move any historical color stages. for(NSString *type in @[@"mixer",@"film"]){BOOL enabled=[type isEqual:@"mixer"]?DYChannelMixerActive(u):DYFilmToolActive(u);if(enabled){DYExportTile *next=makeTile();if(!next)return fail(error,@"无法分配胶片工具缓冲区");BOOL ok=[self renderFilmTool:type source:tile destination:next uniforms:u masks:tools[@"baseMasks"][type]?:@[] entry:entry error:error];if(!ok){[next release];return NO;}replace(next);}if(!apply([@"base:" stringByAppendingString:type]))return NO;} // Schema 1 extra layers (and children inserted after those layers) retain // their old end-of-chain order. Saving does not silently migrate old looks. if(!apply(@"tail"))return NO;return [self copyTile:tile to:dst entry:entry error:error]; }@finally{[originalReference release];[skinReference release];[tile release];} }}} - (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools error:(NSError**)error {@synchronized(self){ if(DYFilmToolActive(u)&&DYFilmSpatialActive(u.film))return fail(error,@"当前胶片含晕光、辉光、颗粒或暗角,无法完整保存到静态 Cube。请保存完整预设,或关闭这些处理后再导出。");for(NSDictionary *node in tools[@"layers"]){DYUniforms layer=DYToolUniforms(node);if([node[@"type"]isEqual:@"film"]&&DYFilmToolActive(layer)&&DYFilmSpatialActive(layer.film))return fail(error,@"新增胶片层含空间或时间处理,无法完整保存到静态 Cube。请保存完整预设。");} for(NSArray *masks in [tools[@"baseMasks"]allValues])if(masks.count)return fail(error,@"当前调色含空间蒙版或跟踪,Cube 无法保存这些信息。请先保存完整预设,或移除蒙版后导出。");for(NSDictionary *node in tools[@"layers"])if([node[@"masks"]count])return fail(error,@"新增工具含蒙版,无法完整导出为 Cube。请保存完整预设。"); _toolDocument=tools;BOOL ok=NO;@try{ok=[self exportLUT:url uniforms:u paths:paths spider:spider error:error];}@finally{_toolDocument=nil;}return ok; }}