diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index f0855309..883bf213 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -127,8 +127,10 @@ export const productionOperationTools = [ ['adopt_production_image','采用你选择的候选,用 reason 记录采用理由,返回画布修订和模板叠层。单图位屏与验图画面一致时沿用复核结论。screensReadyForReview 列出图位已齐、尚未复核当前画面的多图位屏。可用 read_output_screen 查看整屏合成画面。',obj({slotId:slotRef,candidateId:text,fit:optional(fit),reason:optional(text)})], ['retire_production_image','清理你已判为失败的当前图位候选,保留原因、提示词和原请求记录。返工需要旧图时,先让子代理读取再清理。若该图已在画布上,回执会给出应替换的图层。',obj({slotId:slotRef,candidateId:text,reason:text})], ['reconcile_image_slots','按已保存的原操作或原候选号核查结果。未绑定画布时核查本轮项目输出,可用完整图位 id 缩小范围。unknown 继续核查原号,结果有留存时按原号取回,不重新付费。expired 表示原结果已不可取回:网关确认结果过期(HTTP 410)、结果链接下载返回 404 或 410,或原请求在 180 秒恢复预算用完后仍是 unresolved。expired 可以为同图位另备新请求;已派发的原请求仍计入该图位的生图次数上限。',obj({...outputScope,slotIds:optional(ids)})], - ['read_output_screen',`读取整屏合成画面、模板差异摘要、overlayLayers 和 slotGeometry。用 includeTemplateImage 读取模板原屏,用 templateLayerId 查具体图层的完整原值与现值。若返回 nextChangeOffset,可用 templateChangeOffset 继续读差异。subjectBounds 是画布坐标 [x,y,w,h],由放置后的像素与边缘背景的色差估测,并裁到图位可见框内。测不出时由 subjectBoundsReason 说明原因。对位有误时可对照两组 bounds,用 native_call 的 edit.transform 移动或缩放叠层,或用 transform_slot_image 调整候选并采纳,再复核本屏。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。只保留最新一次查看图片。${COPY_IMAGE_SCREEN_GUIDANCE}需要修正时通过 native_catalog 查命令,再用 native_call 编辑叠层,或用 write_copy_fields、transform_slot_image 更新映射内容。`,obj({ + ['read_output_screen',`读取整屏合成画面、模板差异摘要、overlayLayers、slotGeometry 和 annotationLayout。局部查看用 page 和 region(画布坐标 [x,y,w,h]),zoom 为 1–4 倍,图上网格标的是原画布坐标。annotationLayout 提供可见文字、线端点、穿线长度、主体框重叠比例和双向最近距离。用 includeTemplateImage 读取模板原屏,用 templateLayerId 查具体图层的完整原值与现值。若返回 nextChangeOffset,可用 templateChangeOffset 继续读差异。subjectBounds 是画布坐标 [x,y,w,h],由放置后的像素与边缘背景的色差估测,并裁到图位可见框内。测不出时由 subjectBoundsReason 说明原因。对位有误时可对照两组 bounds,用 native_call 的 edit.transform 移动或缩放叠层,或用 transform_slot_image 调整候选并采纳,再复核本屏。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。只保留最新一次查看图片。${COPY_IMAGE_SCREEN_GUIDANCE}需要修正时通过 native_catalog 查命令,再用 native_call 编辑叠层,或用 write_copy_fields、transform_slot_image 更新映射内容。`,obj({ page:optional(page),pages:optional(Type.Array(page)), + region:optional(Type.Tuple([Type.Integer(),Type.Integer(),Type.Integer({minimum:1}),Type.Integer({minimum:1})])), + zoom:optional(Type.Number({minimum:1,maximum:4})), includeTemplateImage:optional(Type.Boolean()),templateLayerId:optional(Type.Integer({minimum:1})),templateChangeOffset:optional(Type.Integer({minimum:0})), })], ['check_output_screens','按企业 Skill 并行复核整屏合成画面、商品实拍、实时文案与叠加图层。pages 从 1 编号,以当前画布实际屏数为准。默认等待结论,自动登记通过和需要修正的屏。问题按图位、原生图层或文案字段定位。wait=false 可用不带 slotIds 的 await_image_slots 收取摘要。',obj({ @@ -1651,10 +1653,11 @@ export async function openProductionOperations(host,{target=host.productionGoal, const pendingSlots=new Set(originals.map(row=>row.slotId)); return [...originals,...results.filter(row=>row.phase!=='none'||!pendingSlots.has(row.slotId))]; }, - async read_output_screen({page=0,pages,includeTemplateImage=false,templateLayerId,templateChangeOffset=0},signal){ + async read_output_screen({page=0,pages,includeTemplateImage=false,templateLayerId,templateChangeOffset=0,region,zoom},signal){ + if(region && pages?.length) throw Error('局部读取请用 page 指定单屏'); const render=async page=>{ const {images=[],overlayLayers,templateFidelity:templateEvidence,...details}=await canvas.detailRender({ - page,templateComparison:true,...(includeTemplateImage?{includeTemplateImage:true}:null), + page,templateComparison:true,...(region?{region,zoom}:null),...(includeTemplateImage?{includeTemplateImage:true}:null), ...(templateLayerId?{templateLayerId}:null), }); const snapshot=await copySnapshot({screenFingerprintPage:page}); @@ -1670,7 +1673,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, })); const screenCopy=extractPageLiveCopy({pageIndex:page,pages:copyPages,fields:visibleCopy}); const previews=await Promise.all(images.map(async image=>{ - if(image.type!=='image')return {image}; + if(image.type!=='image'||(region&&image===images[0]))return {image}; const resized=await resizeImage(Buffer.from(image.data,'base64'),image.mimeType,host.info?.model?.inputLimits?.images?.resize); if(!resized)return {image}; return {image:{type:'image',data:resized.data,mimeType:resized.mimeType},note:formatDimensionNote(resized)}; diff --git a/apps/detail-agent-pi/src/screen-review.mjs b/apps/detail-agent-pi/src/screen-review.mjs index 3f11e752..38b4fe0c 100644 --- a/apps/detail-agent-pi/src/screen-review.mjs +++ b/apps/detail-agent-pi/src/screen-review.mjs @@ -57,8 +57,8 @@ export function normalizeScreenReview({screenReview,templateFidelity,...args}) { return args; } -export function screenFindings({overlayLayers,screenCopy,slots,templateFidelity}) { - const layerIds = new Set([...overlayLayers,...(templateFidelity?.changes??[]),...(templateFidelity?.retainedTemplateText??[])].map(layer => layer.nativeLayerId)); +export function screenFindings({overlayLayers,screenCopy,slots,templateFidelity,annotationLayout}) { + const layerIds = new Set([...overlayLayers,...(annotationLayout?.texts??[]),...(annotationLayout?.lines??[]),...(templateFidelity?.changes??[]),...(templateFidelity?.retainedTemplateText??[])].map(layer => layer.nativeLayerId)); for (const row of templateFidelity?.factConflicts??[]) { for (const id of row.visibleLayerIds??[]) layerIds.add(id); } @@ -67,7 +67,7 @@ export function screenFindings({overlayLayers,screenCopy,slots,templateFidelity} const slotIds = new Set(slots.map(slot => slot.id)); const facts=()=>[ `本屏可用 nativeLayerId ${JSON.stringify(overlayLayers.map(({nativeLayerId,name,text})=>({nativeLayerId,name,text})))}`, - `模板差异及原文图层可用编号 ${JSON.stringify([...layerIds])}`, + `标注及模板差异图层可用编号 ${JSON.stringify([...layerIds])}`, `本屏可用 slotId ${JSON.stringify(numberScreenSlots(slots).map(({id,label,fieldId,slotNumber})=>({slotNumber,slotId:id,label,fieldId})))}`, `本屏可用 field ${JSON.stringify(numberedCopy.map(({field,label,screenFieldNumber})=>({screenFieldNumber,field,label})))}`, SCREEN_REVIEW_REQUIREMENTS, @@ -140,7 +140,7 @@ export function screenFindings({overlayLayers,screenCopy,slots,templateFidelity} } export async function reviewOutputScreen({runAgent, page, screen, references, slots, outputId, variantId, signal}) { - const {revision,screenFingerprint,screenChanged,overlayLayers,overlayGroups,slotGeometry,fieldRequirements,templateFidelity,screenCopy=[]} = screen.details; + const {revision,screenFingerprint,screenChanged,overlayLayers,overlayGroups,slotGeometry,annotationLayout,fieldRequirements,templateFidelity,screenCopy=[]} = screen.details; const images = screen.content.filter(item => item.type === 'image'); if (!screenFingerprint || ![1,2].includes(images.length)) throw Error('未读取到当前屏的实际画面和内容指纹'); if (screenChanged) throw Error('读取画面后本屏已变化,请复查当前屏'); @@ -148,7 +148,7 @@ export async function reviewOutputScreen({runAgent, page, screen, references, sl const {product,photos} = await references(); signal?.throwIfAborted(); const example='最小提交示例 '+JSON.stringify({verdict:'pass',summary:'标注与商品部位对齐,文案符合商品资料。'}); - const {facts,normalize,validate} = screenFindings({overlayLayers,screenCopy,slots,templateFidelity}); + const {facts,normalize,validate} = screenFindings({overlayLayers,screenCopy,slots,templateFidelity,annotationLayout}); let receipt; function prepare(raw) { return validateWorkerArguments('review_output_screen',screenAssessment, @@ -173,13 +173,13 @@ export async function reviewOutputScreen({runAgent, page, screen, references, sl const scope = screenReviewScope(variantId,outputId,page); const instructions = [ '复核整屏成片。第一张是整屏实际画面,如有模板原屏,它位于成片之后,再后面是本款实拍。', - '用 review_output_screen 提交结论、画面依据和修改建议。图片问题填写 location 和已知 slotId,叠层问题填写 overlayLayers 中的 nativeLayerId,正文问题填写 screenCopy 中的 field。', + '用 review_output_screen 提交结论、画面依据和修改建议。图片问题填写 location 和已知 slotId,叠层问题填写 overlayLayers 中的 nativeLayerId,原生标注也可引用 annotationLayout 中的编号,正文问题填写 screenCopy 中的 field。', '每项问题只引用一个编号,从本屏对应清单原样复制。一个问题涉及多个字段时逐项填写。找不到对应图位、叠层或文案字段时,省略编号并用 location 描述画面位置。', OVERLAY_SCREEN_CRITERIA, TEMPLATE_REVIEW_GUIDANCE('顶层 templateStyle'), SCREEN_REVIEW_REQUIREMENTS, ].join('\n'); - const prompt = JSON.stringify({page,revision,product,slots:numberScreenSlots(slots),slotGeometry, + const prompt = JSON.stringify({page,revision,product,slots:numberScreenSlots(slots),slotGeometry,annotationLayout, screenCopy:numberScreenCopy(screenCopy),fieldRequirements,overlayLayers,overlayGroups,templateFidelity,productReferenceCount:photos.length}); const captions = ['当前整屏成片', ...(images.length===2?['模板原屏']:[]), ...photos.map((_,index) => `本款实拍 ${index + 1}`)]; await runAgent(`screen-${page}`, instructions, prompt, [tool], [...images,...photos], scope, captions,signal); diff --git a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md index 681ac865..c6ffae25 100644 --- a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md +++ b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md @@ -34,3 +34,9 @@ read_output_screen 默认提供当前成片、图层差异摘要及可见模板 - 尺寸图按本款资料更新数字和单位,同时对齐尺寸线与端点,保留图示布局。尺寸图不能改为纯文字列表。 - 标题改字后用 `type.info` 读排版边界,检查单独图层上的括号、短线和引线是否需要对位。栅格或智能对象装饰可用 `edit.transform` 整层移位。说明文案也要检查边界和参考线。 - 用 `native_catalog` 查具体参数。编辑后按需回读几何并查看 `read_output_screen` 的实际成图,核对曲线贴合、端点指向、文字溢出和尺寸对应关系。 + +### 尺寸线与引线定位 + +- 标签贴近所属线的中段,给线条和商品主体留出空隙。尺寸线端点和引线指向端落在对应部位的外缘。 +- 需要精确坐标时,用 `read_output_screen` 的 `page`、`region` 和 `zoom` 查看局部,按图中画布刻度读取位置。结合 `annotationLayout` 的穿线、主体框重叠与最近距离定位,按画面确认线与文字的归属。 +- 用 `path.moveAnchors` 移动路径端点、`shape.edit` 调整原生形状、`edit.transform` 移动文字或整层叠图,按需回读合成画面。 diff --git a/apps/detail-agent-pi/test/copy-image-alignment.test.mjs b/apps/detail-agent-pi/test/copy-image-alignment.test.mjs index f199df2e..ec899fb6 100644 --- a/apps/detail-agent-pi/test/copy-image-alignment.test.mjs +++ b/apps/detail-agent-pi/test/copy-image-alignment.test.mjs @@ -133,7 +133,11 @@ test('production delegation and screen rendering use live copy after a direct ca assert.equal(options.includeFilled,true); return {fields:structuredClone(live),pages,revision:2}; }, - detailRender:async({page})=>({page,revision:2,overlayLayers:page===1?overlayLayers:[],images:[]}), + detailRender:async({page,region,zoom})=>({ + page,revision:2,overlayLayers:page===1?overlayLayers:[], + annotationLayout:{texts:[],lines:[],crossings:[]}, + ...(region?{regionPreview:{bounds:region,zoom},images:[{type:'image',mimeType:'image/jpeg',data:'crop'}]}:{images:[]}), + }), readCanvas:async({layer})=>({context:{layers:[{id:layer,visible:true,effectiveVisible:layer!==7}]}}), delta:async()=>{}, },async runDetailAgent(_slot,instructions,prompt){ @@ -151,6 +155,10 @@ test('production delegation and screen rendering use live copy after a direct ca assert.deepEqual(delegated.screenCopy.map(row=>row.text),['加厚桌腿','桌腿与横梁用榫接固定','实木横梁']); live.push({layer:7,page:'P02',field:'hidden',currentText:'已隐藏分组的旧文案'}); const {details,content}=await actions.read_output_screen({page:1}); + const crop=await actions.read_output_screen({page:1,region:[20,30,100,80],zoom:2}); + assert.deepEqual(crop.details.regionPreview,{bounds:[20,30,100,80],zoom:2}); + assert.deepEqual(crop.details.annotationLayout,details.annotationLayout); + assert.deepEqual(crop.content[1],{type:'image',mimeType:'image/jpeg',data:'crop'}); assert.deepEqual(details.overlayLayers,overlayLayers); assert.deepEqual(JSON.parse(content[0].text).overlayLayers,overlayLayers); const multi=await actions.read_output_screen({pages:[0,1]}); diff --git a/apps/detail-agent-pi/test/screen-review.test.mjs b/apps/detail-agent-pi/test/screen-review.test.mjs index 3c8da0aa..51eb9ad9 100644 --- a/apps/detail-agent-pi/test/screen-review.test.mjs +++ b/apps/detail-agent-pi/test/screen-review.test.mjs @@ -121,6 +121,7 @@ async function fixture(t) { state.reads.push(page); if(page>=pages.length)throw Error('此屏不属于当前工作画布'); return {page,revision:state.revision,screenFingerprint:state.fingerprints[page],images:[pixels],fields:[slots[page].fieldId], + annotationLayout:{lines:[{nativeLayerId:501+page,endpoints:[[10,20],[10,80]]}]}, ...(state.overlay?{overlayLayers:[{nativeLayerId:201+page,name:'尺寸标注',text:'45cm',overlapsSlots:[slots[page].fieldId],group:{id:900+page,name:'尺寸组'}}, {nativeLayerId:301+page,name:'尺寸线',overlapsSlots:[slots[page].fieldId],group:{id:900+page,name:'尺寸组'}}, {nativeLayerId:401+page,name:'旧尺寸',text:'旧尺寸',overlapsSlots:[], @@ -251,7 +252,8 @@ test('非当前成品的候选等待验图时直接读取其已保存画布', {t test('screen reviews keep images in the worker and persist findings and passes',async t=>{ const {host,state,journal}=await fixture(t); host.runDetailAgent=async(_id,system,input,[tool],images,scope)=>{ - const {page,revision,product,overlayLayers,overlayGroups,screenCopy,slots}=JSON.parse(input); + const {page,revision,product,overlayLayers,overlayGroups,screenCopy,slots,annotationLayout}=JSON.parse(input); + assert.deepEqual(annotationLayout.lines,[{nativeLayerId:500+page,endpoints:[[10,20],[10,80]]}]); assert.equal(scope,screenReviewScope(variantId,outputId,page)); assert.match(scope,/^product\/review\/[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/); assert.equal(revision,7); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs index 813e4dbd..56a6dd05 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -3052,33 +3052,39 @@ fn subject_bounds( let source = surface.content_bounds(); let pixels = source.intersect(&frame); if pixels.is_empty() { return Err("图位内没有可测像素"); } - let rgb = photocraft_color::PixelFormat::new( - photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::F32, false); + let rgba = photocraft_color::PixelFormat::new( + photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::F32, true); let distance = |a: &[f32], b: &[f32]| { - a.iter().zip(b).map(|(a,b)| (a-b).abs()).fold(0.0_f32, f32::max) + a[..3].iter().zip(&b[..3]).map(|(a,b)| (a-b).abs()).fold(0.0_f32, f32::max) }; let format = surface.format(); let sample = |x,y| { if format.mode == photocraft_color::ColorMode::Rgb { - let mut pixel = [0.0; 4]; + let mut pixel = [0.0, 0.0, 0.0, 1.0]; surface.read_pixel(x, y, &mut pixel[..format.channels()]); - [pixel[0], pixel[1], pixel[2]] + pixel } else { - let pixel = photocraft_raster::convert_pixel(&format, &rgb, &surface.pixel(x,y)); - [pixel[0], pixel[1], pixel[2]] + let pixel = photocraft_raster::convert_pixel(&format, &rgba, &surface.pixel(x,y)); + [pixel[0], pixel[1], pixel[2], pixel[3]] } }; - let background = sample(source.x0, source.y0); - let edge = (source.x0..source.x1).flat_map(|x| [(x,source.y0),(x,source.y1-1)]) - .chain((source.y0..source.y1).flat_map(|y| [(source.x0,y),(source.x1-1,y)])); - if edge.filter(|&(x,y)| distance(&background,&sample(x,y)) > 0.12).count() * 10 - > 2 * (source.width() + source.height()) as usize { + // A resampled image can have a partially transparent fringe around the photograph. + let inset = if source.width().min(source.height()) > 4 { 2 } else { 0 }; + let (left,top,right,bottom) = (source.x0+inset,source.y0+inset,source.x1-inset,source.y1-inset); + let edge = (left..right).flat_map(|x| [(x,top),(x,bottom-1)]) + .chain((top..bottom).flat_map(|y| [(left,y),(right-1,y)])); + let mut opaque_edge = edge.map(|(x,y)| sample(x,y)).filter(|pixel| pixel[3] >= 0.5); + let background = opaque_edge.next().ok_or("图像边缘没有不透明背景样本")?; + let (different,total) = opaque_edge.fold((0,1), |(different,total),pixel| + (different + usize::from(distance(&background,&pixel) > 0.12),total + 1)); + if different * 10 > total { return Err("图像边缘颜色不均匀"); } let mut bounds = photocraft_geom::Rect::new(0,0,0,0); for y in pixels.y0..pixels.y1 { for x in pixels.x0..pixels.x1 { - if distance(&background,&sample(x,y)) > 0.12 { + let pixel = sample(x,y); + if pixel[3] >= 0.5 && distance(&background,&pixel) > 0.12 { bounds = bounds.union(&photocraft_geom::Rect::new(x,y,x+1,y+1)); } } @@ -3099,6 +3105,12 @@ fn subject_bounds_measure_flat_background_and_reject_uneven_edges() { assert_eq!(subject_bounds(&surface, Rect::new(40, 20, 110, 100)), Ok([40, 38, 44, 43])); surface.fill_rect(Rect::new(10, 20, 60, 100), &[0.3, 0.4, 0.5, 1.0]); assert_eq!(subject_bounds(&surface, frame), Err("图像边缘颜色不均匀")); + + let mut transformed = photocraft_raster::Surface::new(PixelFormat::RGBA8); + transformed.fill_rect(frame, &[0.0, 0.0, 0.0, 0.25]); + transformed.fill_rect(Rect::new(12, 22, 108, 98), &[1.0, 1.0, 1.0, 1.0]); + transformed.fill_rect(Rect::new(32, 38, 84, 81), &[0.2, 0.1, 0.1, 1.0]); + assert_eq!(subject_bounds(&transformed, frame), Ok([32, 38, 52, 43])); } fn read_screen_preview(native: &Document, input: &Value) -> R { @@ -3159,7 +3171,21 @@ fn read_production_screen_with( let with_image = input["signatureOnly"] != true; let check_blank = input["preflight"] == true && fields.is_empty(); if !with_image && !check_blank { return Ok(receipt); } - let jpeg = preview(area)?; + let jpeg = if input["region"].is_null() { + preview(area)? + } else { + let [x,y,w,h] = serde_json::from_value::<[i32;4]>(input["region"].clone()) + .map_err(|_| "region 必须是画布坐标 [x,y,w,h]")?; + if w <= 0 || h <= 0 || x < area.x0 || y < area.y0 + || i64::from(x) + i64::from(w) > i64::from(area.x1) + || i64::from(y) + i64::from(h) > i64::from(area.y1) { + return Err("region 必须完整落在当前屏内".into()); + } + let zoom = input["zoom"].as_f64().unwrap_or(1.0).clamp(1.0,4.0); + let (jpeg, transform) = screen_preview::render_region(native, photocraft_geom::Rect::new(x,y,x+w,y+h), zoom)?; + receipt["regionPreview"] = transform; + std::sync::Arc::new(jpeg) + }; if check_blank { let pixels = photocraft_codecs::decode(&jpeg).map_err(|_| "实际画面无法读取")? .convert(photocraft_codecs::ChannelLayout::Gray, photocraft_codecs::SampleType::U8); @@ -3183,6 +3209,10 @@ fn read_production_screen_with( row }).collect::>()); add_annotation_subject_hits(&mut receipt); + if !input["candidatePreview"].is_object() { + receipt["annotationLayout"] = photocraft_ui_egui::jiansun::production_facts::annotation_layout( + native, area, &receipt["slotGeometry"]); + } if input["candidatePreview"].is_object() { receipt["imageSlots"] = json!(page["mapping"]["fields"].as_array().into_iter().flatten() .filter(|field| field["kind"] == "image").filter_map(|field| field["slotId"].as_str()).collect::>()); @@ -7646,3 +7676,15 @@ mod tests { assert!(!unfinished.join("manifest.json").exists()); } } + +#[test] +#[ignore = "requires a local copy of a saved production canvas"] +fn jiansun_annotation_replay() { + let path = std::env::var_os("JIANSUN_ANNOTATION_REPLAY").expect("set the path to the replay copy"); + let native = photocraft_format::load_path(Path::new(&path)).unwrap(); + let meta = mapping(&native).unwrap(); + for index in 0..meta["outputs"].as_array().unwrap().len() { + let receipt = read_screen_preview(&native,&json!({"page":index})).unwrap(); + println!("{}", json!({"page":index,"annotationLayout":receipt["annotationLayout"],"slotGeometry":receipt["slotGeometry"]})); + } +} diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_screen_preview.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_screen_preview.rs index e41d1fab..88bfe711 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_screen_preview.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_screen_preview.rs @@ -41,13 +41,115 @@ pub(super) fn render(native: &Document, area: Rect) -> R> { pub(super) fn render_at_limit(native: &Document, area: Rect, limit: f64) -> R> { let scale = (limit / f64::from(area.width().max(area.height()))).min(1.0); let [w, h] = [area.width(), area.height()].map(|size| (f64::from(size) * scale).round().max(1.0) as u32); - let rendered = photocraft_ui_egui::gpu_canvas::background_compose::render(native, area, w, h); - let rgb = rendered + render_pixels(native, area, w, h, None) +} + +pub(super) fn render_region(native: &Document, area: Rect, zoom: f64) -> R<(Vec, Value)> { + let scale = zoom.min(1536.0 / f64::from(area.width().max(area.height()))); + let [w, h] = [area.width(), area.height()].map(|n| (f64::from(n) * scale).round().max(1.0) as u32); + let step = (100.0 / scale).ceil() as i32; + let jpeg = render_pixels(native, area, w, h, Some(step))?; + Ok(( + jpeg, + serde_json::json!({"bounds":[area.x0,area.y0,area.width(),area.height()], + "pixelSize":[w,h],"gridStep":step}), + )) +} + +fn grid_pixel(coordinate: i32, origin: i32, extent: u32, pixels: u32) -> u32 { + ((f64::from(coordinate - origin) * f64::from(pixels) / f64::from(extent)).floor() as u32).min(pixels - 1) +} + +fn grid(rgb: &mut [u8], area: Rect, w: u32, h: u32, step: i32) { + const DIGITS: [[u8; 5]; 11] = [ + [7, 5, 5, 5, 7], + [2, 6, 2, 2, 7], + [7, 1, 7, 4, 7], + [7, 1, 7, 1, 7], + [5, 5, 7, 1, 1], + [7, 4, 7, 1, 7], + [7, 4, 7, 5, 7], + [7, 1, 2, 2, 2], + [7, 5, 7, 5, 7], + [7, 5, 7, 1, 7], + [0, 0, 7, 0, 0], + ]; + let mut pixel = |x: u32, y: u32, color: [u8; 3]| { + if x < w && y < h { + let i = 3 * (y * w + x) as usize; + rgb[i..i + 3].copy_from_slice(&color); + } + }; + for (vertical, origin, end, extent, pixels) in [(true, area.x0, area.x1, area.width(), w), (false, area.y0, area.y1, area.height(), h)] { + for coord in (origin..end).step_by(step as usize) { + let offset = grid_pixel(coord, origin, extent, pixels); + let length = if vertical { h } else { w }; + for i in (0..length).step_by(4) { + let (x, y) = if vertical { (offset, i) } else { (i, offset) }; + pixel(x, y, [24, 110, 180]); + } + let (x, y) = if vertical { (offset + 2, 2) } else { (2, offset + 14) }; + for (index, digit) in coord.to_string().bytes().enumerate() { + let rows = DIGITS[if digit == b'-' { 10 } else { (digit - b'0') as usize }]; + for (row, mask) in rows.into_iter().enumerate() { + for col in 0..8 { + let on = col < 6 && mask & (1 << (2 - col / 2)) != 0; + let color = if on { [0, 40, 95] } else { [255, 255, 255] }; + for dy in 0..2 { + pixel(x + index as u32 * 8 + col, y + row as u32 * 2 + dy, color); + } + } + } + } + } + } +} + +fn render_pixels(native: &Document, area: Rect, w: u32, h: u32, step: Option) -> R> { + let source_w = w.min(area.width()); + let source_h = h.min(area.height()); + let rendered = photocraft_ui_egui::gpu_canvas::background_compose::render(native, area, source_w, source_h); + let mut rgb: Vec = rendered .px .into_iter() .flat_map(|[r, g, b, alpha]| [r, g, b].map(|value| ((value * alpha + 1.0 - alpha).clamp(0.0, 1.0) * 255.0 + 0.5) as u8)) .collect(); + if (source_w, source_h) != (w, h) { + let source = image::RgbImage::from_raw(source_w, source_h, rgb).ok_or("实际画面无法读取")?; + rgb = image::imageops::resize(&source, w, h, image::imageops::FilterType::Triangle).into_raw(); + } + if let Some(step) = step { + grid(&mut rgb, area, w, h, step); + } let preview = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, rgb).map_err(|_| "实际画面无法读取")?; let options = photocraft_codecs::EncodeOptions { jpeg_quality: 85, ..Default::default() }; photocraft_codecs::encode(&preview, photocraft_codecs::Format::Jpeg, &options).map_err(|error| format!("实际画面无法编码:{error}")) } + +#[test] +fn region_grid_uses_canvas_coordinates_and_bounded_pixels() { + use photocraft_color::{ColorMode, SampleType}; + use photocraft_doc::Size; + assert_eq!(grid_pixel(250, 200, 100, 400), 200); + let mut doc = Document::new("test", Size::new(2000, 2000), ColorMode::Rgb, SampleType::U8); + let mut cache = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); + cache.fill_rect(Rect::new(249, 320, 251, 350), &[0.0, 0.0, 0.0, 1.0]); + doc.layers.push(photocraft_doc::Layer::new( + "test line", + photocraft_doc::LayerContent::Shape(photocraft_doc::ShapeLayer { + path: photocraft_doc::Path::new(vec![photocraft_doc::Subpath::polygon(&[(249.0, 320.0), (251.0, 320.0), (251.0, 350.0), (249.0, 350.0)])]), + live: Some(photocraft_doc::LiveShape::Line { from: [250.0, 320.0], to: [250.0, 350.0], weight: 2.0 }), + fill: Some(photocraft_doc::Fill::Solid(photocraft_color::Color::BLACK)), + cache: Some(cache), + ..Default::default() + }), + )); + let (jpeg, enlarged) = render_region(&doc, Rect::new(200, 300, 300, 400), 4.0).unwrap(); + assert_eq!(enlarged["pixelSize"], serde_json::json!([400, 400])); + let pixels = photocraft_codecs::decode(&jpeg).unwrap().convert(photocraft_codecs::ChannelLayout::Rgb, photocraft_codecs::SampleType::U8); + let at = |x: usize, y: usize| &pixels.data()[3 * (y * 400 + x)..][..3]; + assert!(at(200, 121).iter().all(|channel| *channel < 70)); + assert!(at(185, 121).iter().all(|channel| *channel > 220)); + let (_, transform) = render_region(&doc, Rect::new(200, 300, 1800, 1900), 4.0).unwrap(); + assert_eq!(transform["pixelSize"], serde_json::json!([1536, 1536])); +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_facts.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_facts.rs index b075156a..fccab909 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_facts.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_facts.rs @@ -431,3 +431,6 @@ fn screen_overlays_identify_dimension_group_and_copy_below_slot() { let rows = screen_overlay_layers(&doc, &meta, doc.bounds(), None); assert!(rows[0].get("belowSlot").is_none()); } + +mod annotation_layout; +pub use annotation_layout::annotation_layout; diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_facts/annotation_layout.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_facts/annotation_layout.rs new file mode 100644 index 00000000..25fd027d --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_facts/annotation_layout.rs @@ -0,0 +1,281 @@ +use super::{Document, LayerContent, Rect, Value, json, path_visible}; +use photocraft_doc::LiveShape; + +type Point = (f64, f64); + +fn edges(r: Rect) -> [f64; 4] { + [r.x0, r.y0, r.x1, r.y1].map(f64::from) +} + +fn clip(a: Point, b: Point, [l, t, r, bottom]: [f64; 4]) -> Option<(f64, f64)> { + let (mut start, mut end) = (0.0_f64, 1.0_f64); + for (origin, delta, low, high) in [(a.0, b.0 - a.0, l, r), (a.1, b.1 - a.1, t, bottom)] { + if delta == 0.0 { + if origin < low || origin > high { + return None; + } + continue; + } + let u = (low - origin) / delta; + let v = (high - origin) / delta; + start = start.max(u.min(v)); + end = end.min(u.max(v)); + } + (end >= start).then_some((start, end)) +} + +// Intersect the text box with the perpendicular strip of the stroke, then +// project onto the segment. The resulting length is in canvas pixels. +fn crossing_length(a: Point, b: Point, corners: [Point; 4], radius: f64) -> f64 { + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let length = dx.hypot(dy); + if length == 0.0 { + return 0.0; + } + let coordinates = |(x, y): Point| (((x - a.0) * dx + (y - a.1) * dy) / length, ((y - a.1) * dx - (x - a.0) * dy) / length); + let corners = corners.map(coordinates); + let (mut lo, mut hi) = (length, 0.0_f64); + for i in 0..4 { + let ((x, y), (u, v)) = (corners[i], corners[(i + 1) % 4]); + if y.abs() <= radius { + lo = lo.min(x); + hi = hi.max(x); + } + for border in [-radius, radius] { + if (y < border && border < v) || (v < border && border < y) { + let crossing = x + (u - x) * (border - y) / (v - y); + lo = lo.min(crossing); + hi = hi.max(crossing); + } + } + } + (hi.min(length) - lo.max(0.0)).max(0.0) +} + +fn measure(a: Point, b: Point, [l, t, r, bot]: [f64; 4], radius: f64) -> (f64, f64) { + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let length = dx.hypot(dy); + let corners = [(l, t), (r, t), (r, bot), (l, bot)]; + let hit = crossing_length(a, b, corners, radius); + if clip(a, b, [l, t, r, bot]).is_some() { + return (hit, 0.0); + } + let mut distance = [a, b].into_iter().map(|(x, y)| (x - x.clamp(l, r)).hypot(y - y.clamp(t, bot))).fold(f64::INFINITY, f64::min); + if length > 0.0 { + for (x, y) in corners { + let u = (((x - a.0) * dx + (y - a.1) * dy) / (length * length)).clamp(0.0, 1.0); + distance = distance.min((x - a.0 - u * dx).hypot(y - a.1 - u * dy)); + } + } + (hit, distance) +} + +struct Line { + id: u64, + subpath: usize, + endpoints: [Point; 2], + segments: Vec<[Point; 2]>, + width: f64, +} + +fn line_geometry(id: u64, shape: &photocraft_doc::ShapeLayer, max_bar_width: f64) -> impl Iterator + '_ { + let stroke = shape.stroke.as_ref().filter(|s| s.width > 0.0 && s.opacity > 0.0).map(photocraft_vector::stroke_style); + let make_bar = move |subpath, a, b, width| Line { id, subpath, endpoints: [a, b], segments: vec![[a, b]], width }; + let native_line = match shape.live.as_ref() { + Some(LiveShape::Line { from: [x, y], to: [u, v], weight }) if shape.fill.is_some() => Some(make_bar(0, (*x, *y), (*u, *v), *weight)), + _ => None, + }; + let paths = if native_line.is_some() { Vec::new() } else { photocraft_vector::flatten_path(&shape.path, 0.25) }; + native_line.into_iter().chain(paths.into_iter().enumerate().filter_map(move |(subpath, path)| { + if path.closed { + if shape.fill.is_none() && stroke.is_none() { + return None; + } + // The four straight edges of a thin rectangle can be rotated in canvas space. + let [a, b, c, d]: [Point; 4] = path.pts.as_slice().try_into().ok()?; + let delta = |(x, y): Point, (u, v): Point| (u - x, v - y); + let (ab, bc, cd, da) = (delta(a, b), delta(b, c), delta(c, d), delta(d, a)); + let (long, short) = (ab.0.hypot(ab.1), bc.0.hypot(bc.1)); + if short == 0.0 + || long == 0.0 + || (ab.0 * bc.0 + ab.1 * bc.1).abs() > 0.01 * long * short + || (ab.0 + cd.0).hypot(ab.1 + cd.1) > 0.25 + || (bc.0 + da.0).hypot(bc.1 + da.1) > 0.25 + { + return None; + } + let mid = |(x, y): Point, (u, v): Point| ((x + u) / 2.0, (y + v) / 2.0); + let outline = stroke.as_ref().map_or(0.0, |s| s.width); + if long >= 8.0 * short && short + outline <= max_bar_width { + return Some(make_bar(subpath, mid(a, d), mid(b, c), short + outline)); + } + if short >= 8.0 * long && long + outline <= max_bar_width { + return Some(make_bar(subpath, mid(a, b), mid(c, d), long + outline)); + } + return None; + } + let stroke = stroke.as_ref()?; + let endpoints = [*path.pts.first()?, *path.pts.last()?]; + let parts = if stroke.dashes.is_empty() { vec![path] } else { photocraft_vector::stroke::dash_polyline(&path, &stroke.dashes, stroke.dash_offset) }; + let segments = parts.iter().flat_map(|p| p.pts.windows(2).map(|pair| [pair[0], pair[1]])).collect(); + Some(Line { id, subpath, endpoints, segments, width: stroke.width }) + })) +} + +pub fn annotation_layout(doc: &Document, area: Rect, slots: &Value) -> Value { + const LIMIT: usize = 48; + let max_bar_width = f64::from(area.width().min(area.height())) / 32.0; + let mut words = Vec::new(); + let mut lines = Vec::new(); + let mut truncated = false; + for (path, _, layer) in doc.walk() { + if !matches!(&layer.content, LayerContent::Text(_) | LayerContent::Shape(_)) { + continue; + } + if !path_visible(doc, &path) || layer.fill_opacity == 0.0 { + continue; + } + let bounds = photocraft_compose::layer_bounds(layer, doc.bounds()); + let visible = bounds.intersect(&area); + if visible.is_empty() { + continue; + } + match &layer.content { + LayerContent::Text(text) => { + if words.len() == LIMIT { + truncated = true; + continue; + } + let text_preview: String = text.text.chars().take(240).collect(); + truncated |= text_preview.len() < text.text.len(); + words.push((layer.id.0, bounds, visible, text_preview)); + } + LayerContent::Shape(shape) => { + for line in line_geometry(layer.id.0, shape, max_bar_width) { + let [l, t, r, b] = edges(area); + let radius = line.width / 2.0; + if !line.segments.iter().any(|&[a, z]| clip(a, z, [l - radius, t - radius, r + radius, b + radius]).is_some()) { + continue; + } + if lines.len() == LIMIT { + truncated = true; + break; + } + lines.push(line); + } + } + _ => {} + } + } + let subjects: Vec<_> = slots + .as_array() + .into_iter() + .flatten() + .filter_map(|slot| { + let [x, y, w, h] = serde_json::from_value::<[i32; 4]>(slot["subjectBounds"].clone()).ok()?; + Some((&slot["slotId"], Rect::new(x, y, x + w, y + h))) + }) + .collect(); + let mut line_nearest = vec![None; lines.len()]; + let mut crossings = Vec::new(); + let texts: Vec<_> = words + .iter() + .map(|(id, bounds, visible, text)| { + let mut nearest = None; + for (index, line) in lines.iter().enumerate() { + let (mut hit, mut distance) = (0.0, f64::INFINITY); + let [l, t, r, b] = edges(area); + let radius = line.width / 2.0; + for &[a, z] in &line.segments { + let Some((u, v)) = clip(a, z, [l - radius, t - radius, r + radius, b + radius]) else { + continue; + }; + let point = |s| (a.0 + (z.0 - a.0) * s, a.1 + (z.1 - a.1) * s); + let (part, gap) = measure(point(u), point(v), edges(*visible), radius); + hit += part; + distance = distance.min(gap); + } + if !distance.is_finite() { + continue; + } + if nearest.is_none_or(|(_, _, gap)| distance < gap) { + nearest = Some((line.id, line.subpath, distance)); + } + if line_nearest[index].is_none_or(|(_, gap)| distance < gap) { + line_nearest[index] = Some((*id, distance)); + } + if hit > 0.0 { + if crossings.len() < LIMIT { + crossings.push(json!({"textLayerId":id,"lineLayerId":line.id,"subpath":line.subpath,"length":hit})); + } else { + truncated = true; + } + } + } + let area = |r: Rect| f64::from(r.width()) * f64::from(r.height()); + let overlaps: Vec<_> = subjects + .iter() + .filter_map(|(slot, subject)| { + let intersection = visible.intersect(subject); + (!intersection.is_empty()).then(|| json!({"slotId":slot,"ratio":area(intersection)/area(*bounds)})) + }) + .collect(); + json!({"nativeLayerId":id,"text":text,"bounds":[bounds.x0,bounds.y0,bounds.width(),bounds.height()], + "subjectOverlap":overlaps,"nearestLine":nearest.map(|(id,subpath,distance)| json!({"nativeLayerId":id,"subpath":subpath,"distance":distance}))}) + }) + .collect(); + let lines: Vec<_> = lines + .iter() + .zip(line_nearest) + .map(|(line, nearest)| { + json!({ + "nativeLayerId":line.id,"subpath":line.subpath,"endpoints":line.endpoints, + "width":line.width,"nearestText":nearest.map(|(id,distance)| json!({"nativeLayerId":id,"distance":distance})) + }) + }) + .collect(); + json!({"texts":texts,"lines":lines,"crossings":crossings,"truncated":truncated, + "distanceBasis":"centerlineToVisibleTextBounds","crossingBasis":"projectedStrokeStripInsideTextBounds","subjectBasis":"subjectBounds"}) +} + +#[test] +fn annotation_geometry_crossing_and_diagonal_distance() { + assert_eq!(measure((0., 5.), (20., 5.), [5., 0., 15., 10.], 1.), (10., 0.)); + assert!((measure((0., 3.), (4., 0.), [5., 5., 10., 10.], 0.).1 - 4.6).abs() < 1e-9); + assert_eq!(clip((0., 0.), (1., 1.), [5., 5., 10., 10.]), None); +} + +#[test] +fn annotation_layout_measures_subject_overlap_and_excludes_offscreen_layers() { + use photocraft_color::{ColorMode, PixelFormat, SampleType}; + use photocraft_doc::{Layer, ShapeLayer, Size, TextLayer}; + use photocraft_raster::Surface; + let mut doc = Document::new("annotation", Size::new(100, 100), ColorMode::Rgb, SampleType::U8); + let text = |name: &str, bounds| { + let mut cache = Surface::new(PixelFormat::RGBA8); + cache.fill_rect(bounds, &[0.0, 0.0, 0.0, 1.0]); + Layer::new(name, LayerContent::Text(TextLayer { text: name.into(), cache: Some(cache), ..Default::default() })) + }; + let label = text("尺寸", Rect::new(10, 10, 30, 20)); + let id = label.id.0; + let mut cache = Surface::new(PixelFormat::RGBA8); + cache.fill_rect(Rect::new(19, 0, 21, 40), &[0.0, 0.0, 0.0, 1.0]); + let line = Layer::new( + "原生线", + LayerContent::Shape(ShapeLayer { + live: Some(LiveShape::Line { from: [20.0, 0.0], to: [20.0, 40.0], weight: 2.0 }), + fill: Some(photocraft_doc::Fill::Solid(photocraft_color::Color::BLACK)), + cache: Some(cache), + ..Default::default() + }), + ); + let line_id = line.id.0; + doc.layers.extend([label, line, text("屏外", Rect::new(10, 60, 30, 70))]); + let data = annotation_layout(&doc, Rect::new(0, 0, 100, 50), &json!([{"slotId":"a","subjectBounds":[20,10,10,10]}])); + assert_eq!(data["texts"].as_array().unwrap().len(), 1); + assert_eq!(data["texts"][0]["nativeLayerId"], id); + assert_eq!(data["texts"][0]["subjectOverlap"][0]["ratio"], 0.5); + assert_eq!(data["lines"][0]["nearestText"]["distance"], 0.0); + assert_eq!(data["texts"][0]["nearestLine"]["nativeLayerId"], line_id); + assert_eq!(data["crossings"][0]["length"], 10.0); +}