diff --git a/app_ui.go b/app_ui.go index 06db802..6e31cd3 100644 --- a/app_ui.go +++ b/app_ui.go @@ -6523,6 +6523,17 @@ func (a *app) autoSetup(full bool) { } logf("Auto setup (%s): starting from scratch.", map[bool]string{true: "EXTENSIVE", false: "QUICK"}[full]) + var acceptedOwner *calibrationOwner + var dualSource356 *dualDetectSource356 + if !a.dualWorkflowAvailable356()&&a.dualDepthNeedsPair356(){logf("Auto setup stopped: reconnect the second webcam to refresh existing dual depth. It was not discarded for a single-camera reset.");return} + if a.dualWorkflowAvailable356() { + logf("Auto setup: two webcams available. Measuring dual first, then Detect on its exact LEFT photo. Prior project stays until an accepted handoff.") + acceptedOwner,dualSource356=a.dualFreshPrep356() + if acceptedOwner==nil{return} + } + n:=0 + next:=func(name string){n++;step(n,name)} + if dualSource356==nil { archiveEpoch, archiveTicket := calibrationStopEpoch.Load(), cameraCommandWanted.Load() archivePlayer := a.pl snapPath, snapProj := a.hcProjectSnapshot() @@ -6544,8 +6555,7 @@ func (a *app) autoSetup(full bool) { if !ok { return } - n := 0 - next := func(name string) { n++; step(n, name) } + next("Projector") if !a.projOpen { a.uiWait(func() { a.openProjector() }) @@ -6564,7 +6574,6 @@ func (a *app) autoSetup(full bool) { return } - var failedSteps []string next("Measure projector area") reachOwner := a.calibrationOwnerSnapshot() @@ -6580,11 +6589,13 @@ func (a *app) autoSetup(full bool) { if detectSource == nil || detectSource.player != archivePlayer || detectSource.project != snapProj || detectSource.path != snapPath || detectSource.epoch != archiveEpoch || detectSource.ticket != archiveTicket { return } - acceptedOwner := a.autoDetectPrepOwner(detectSource) + acceptedOwner = a.autoDetectPrepOwner(detectSource) if acceptedOwner == nil { return } - next("Calibrate projector image") + } // Single-camera fresh flow. Dual flow has already published its exact-source Detect destination. + var failedSteps []string + next("Calibrate projector image") fallbackScanRan := false if a.st.Indoor { logf("Auto setup Indoors: measuring stripes FIRST. No global fitting dots are projected on unknown furniture. A webcam image or object label alone cannot certify a flat plane; no flat-only dot guarantee is claimed for final verification markers.") @@ -6648,8 +6659,13 @@ func (a *app) autoSetup(full bool) { } } - if calibrationAccepted(a.pl.P) { - logf("Auto setup: verifying the new map against the wall (the Check-calibration measurement)...") + if dualSource356!=nil { + // Calibration changed projector mapping, not the frozen photo or its outlines. + // Re-save from the owned capture with exact photo validation, never hash laundering. + if !a.dualInstallOwned356(acceptedOwner,dualSource356,false){return} + } + if calibrationAccepted(a.pl.P) { + logf("Auto setup: verifying the new map against the wall (the Check-calibration measurement)...") a.checkCalibrationOwned(acceptedOwner) if cameraCommandSuperseded() || !a.calibrationOwnerCurrent(acceptedOwner) { return diff --git a/auto_detect_owned_windows.go b/auto_detect_owned_windows.go index 81e567a..db25bec 100644 --- a/auto_detect_owned_windows.go +++ b/auto_detect_owned_windows.go @@ -16,6 +16,7 @@ var autoDetectLockedCheckpoint = func() {} type autoDetectHandoff struct { mu sync.Mutex source, result *calibrationOwner + dual356 *dualDetectSource356 } func (a *app) autoDetectPrepOwner(source *calibrationOwner) *calibrationOwner { @@ -68,9 +69,13 @@ func (a *app) loadAutoDetectProject(i int, h *autoDetectHandoff) { logf("Auto Detect load: %v", e) return } - if p.Map.Mode != "identity" || len(p.Map.Pairs) > 0 || p.Scan != nil || p.Map.Opus != nil || len(p.Surfaces) == 0 { - return - } + if h.dual356!=nil { + if p.Scan!=nil||p.Map.Opus!=nil||len(p.Surfaces)==0||p.Depth==nil||p.DepthMetric==nil{return} + if e:=h.dual356.verifyPhoto356(p.Depth.SourceFile,p.Scene.W,p.Scene.H);e!=nil{logf("Dual handoff source: %v",e);return} + if depthAuthoringSHA(p)!=p.Depth.AuthoringSHA256||p.DepthMetric.SourceSHA256!=p.Depth.SourceSHA256{return} + } else if p.Map.Mode != "identity" || len(p.Map.Pairs) > 0 || p.Scan != nil || p.Map.Opus != nil || len(p.Surfaces) == 0 { + return + } for _, f := range []string{carryPath(pe.Path), calibPath(pe.Path), overlayPath(pe.Path), scenesPath(pe.Path)} { if _, e := os.Stat(f); !os.IsNotExist(e) { logf("Auto Detect refuses inherited state beside fresh project: %s", f) diff --git a/calibrun.go b/calibrun.go index a1ab59c..41937c5 100644 --- a/calibrun.go +++ b/calibrun.go @@ -535,9 +535,16 @@ func (a *app) calibrate() { a.calibrateMode("quick") } func (a *app) calibrateMode(mode string) { end := calibrationFlowBegin("fresh calibration") defer end() - if owner := a.freshCalibrationPrepOwner(); owner != nil && !cameraCommandSuperseded() { - a.calibrateModeMeasuredOwned(mode, owner) - } + if !a.dualWorkflowAvailable356()&&a.dualDepthNeedsPair356(){logf("Fresh calibration stopped: reconnect the second webcam. Existing dual depth was not discarded.");return} + if a.dualWorkflowAvailable356(){ + owner,dual:=a.dualFreshPrep356();if owner==nil{return} + a.calibrateModeMeasuredOwned(mode,owner) + if !cameraCommandSuperseded()&&a.calibrationOwnerCurrent(owner){a.dualInstallOwned356(owner,dual,false)} + return + } + if owner := a.freshCalibrationPrepOwner(); owner != nil && !cameraCommandSuperseded() { + a.calibrateModeMeasuredOwned(mode, owner) + } } func (a *app) calibrateModeMeasured(mode string) { a.calibrateModeMeasuredOwned(mode, a.calibrationOwnerSnapshot()) diff --git a/common.go b/common.go index e0e36bd..c40fb10 100644 --- a/common.go +++ b/common.go @@ -11,7 +11,7 @@ import ( "time" ) -const version = "0.98.355-experimental1" +const version = "0.98.356-experimental1" const appDisplayName = "Projection Mapper - Built by Instinct" diff --git a/detect.go b/detect.go index a9814ec..5eccdfc 100644 --- a/detect.go +++ b/detect.go @@ -168,7 +168,12 @@ func (a *app) detectModeHandoff(askUser, room bool, prov string, freshReach *fre var snapCam string var snapRes [2]int path := os.Getenv("PM_DETECT_PHOTO") - if path != "" { + if handoff!=nil&&handoff.dual356!=nil { + path=handoff.dual356.path + snapCam=handoff.dual356.camera + snapRes=handoff.dual356.resolution + fromWebcam=true + } else if path != "" { logf("Detect: using the photo from PM_DETECT_PHOTO") } else if !askUser || yesNo("Detect with Gemini", "Take a fresh photo with the webcam now?\n\nYes = webcam photo (best: it lines up with Calibrate; point the camera at the house and keep it steady).\nNo = choose a photo file instead.") { @@ -247,7 +252,11 @@ func (a *app) detectModeHandoff(askUser, room bool, prov string, freshReach *fre var scope *roiScope var roiOK bool - path, scope, roiOK = a.detectScopeROIWithFreshReach(path, freshReach) + if handoff!=nil&&handoff.dual356!=nil { + // Captured white/black stereo frames own reach, not a stale single-camera ROI. + // Keep the canonical pixels and full normalized camera coordinates unchanged. + roiOK=true + } else {path, scope, roiOK = a.detectScopeROIWithFreshReach(path, freshReach)} if !roiOK { return } @@ -410,7 +419,7 @@ func (a *app) detectModeHandoff(askUser, room bool, prov string, freshReach *fre if orLoadKey() != "" { cloud = "openrouter" } - if cloud != "" && yesNoDestructive("Room detect", ask) { + if (handoff==nil||handoff.dual356==nil) && cloud != "" && yesNoDestructive("Room detect", ask) { prev := os.Getenv("PM_DETECT_PHOTO") os.Setenv("PM_DETECT_PHOTO", path) defer os.Setenv("PM_DETECT_PHOTO", prev) @@ -721,7 +730,13 @@ func (a *app) detectBuildAndSave(dr detRun) { return } } - moveMasks(p, out) + if dr.Handoff!=nil&&dr.Handoff.dual356!=nil { + if e:=dr.Handoff.dual356.verifyPhoto356(path,p.Scene.W,p.Scene.H);e!=nil {logf("Dual Detect source refused: %v",e);return} + // Detection geometry came from this exact source. Discard independent AI depth, + // never substitute it for the already-captured stereo result. + p.Depth=nil;p.DepthMetric=nil;p.DepthProps=nil + } + moveMasks(p, out) if p.Depth != nil { if ownedSource == "" { logf("Detect depth source is not an owned stage receipt; publication refused") @@ -743,8 +758,14 @@ func (a *app) detectBuildAndSave(dr detRun) { p.Depth.AuthoringSHA256 = depthAuthoringSHA(p) p.Depth.PhotoAuthoringSHA256 = depthPhotoAuthoringSHA(p) } - p.PhotoCam = snapCam - if err := p.save(out); err != nil { + p.PhotoCam = snapCam + if dr.Handoff!=nil&&dr.Handoff.dual356!=nil { + d:=dr.Handoff.dual356 + if e:=d.verifyPhoto356(path,p.Scene.W,p.Scene.H);e!=nil{logf("Dual Detect final source check: %v",e);return} + dualDir:=filepath.Join(filepath.Dir(d.path),fmt.Sprintf("detected-depth-%d",time.Now().UnixNano())) + if e:=SaveDualDepthToProject(p,d.capture.Room,d.capture.Photo,dualDir,true);e!=nil{logf("Dual Detect project transaction stopped: %v",e);return} + } + if err := p.save(out); err != nil { logf("ERROR could not save the detected project: %v", err) if p.Depth != nil { os.Remove(p.Depth.SourceFile) diff --git a/dual_capture_windows.go b/dual_capture_windows.go index a935e2a..8b5fdc2 100644 --- a/dual_capture_windows.go +++ b/dual_capture_windows.go @@ -913,7 +913,21 @@ func dualWaitSyncedPair(ctx context.Context, rig *captureRigLease, prevSeq [2]ui // self-calibration by projecting multi-frequency phase-shift patterns onto empty // wall space and room surfaces, solving the 3D trinocular rig, reconstructing // dense 3D room depth + surface normals, and activating 3D depth across all engines. +// Capture-only mode returns a source-bound result after BOTH drivers and the +// projector presentation have been released. It never installs old outlines +// onto a new camera photo. The owning workflow decides the destination later. +type dualWorkflowCapture356 struct { + Room *DualRoom3DResult + Photo image.Image + LeftID, RightID string +} func (a *app) dualAutoWallSelfCalibrate() { + a.queueCameraCommand(func(){end:=calibrationFlowBegin("dual source-bound setup");defer end();a.dualFreshPrep356()}) +} +func (a *app) dualAutoWallSelfCalibrate356(result chan<- *dualWorkflowCapture356) { + launched356:=false + defer func(){if result!=nil&&!launched356{result<-nil}}() + logf("Dual 3D auto-calibration requested (experimental; physical capture sequencing remains unqualified).") _, infos := U.camSnapshot() dualUI.Lock() @@ -958,7 +972,10 @@ func (a *app) dualAutoWallSelfCalibrate() { dualUI.Unlock() a.humanRefresh() - go func() { + launched356=true + go func() { + var capture356 *dualWorkflowCapture356 + defer func(){if result!=nil{result<-capture356}}() defer cancel() var presentation *windowsCapturePresentation @@ -966,7 +983,9 @@ func (a *app) dualAutoWallSelfCalibrate() { defer clearProj() - lease, err := dualAcquire(ctx, l, r, "dual-active-wall-3d", map[string]int{l: 640, r: 640}, 6*time.Second, "dual webcam 3D wall self-calibration") + leftWidth356:=640 + if result!=nil{leftWidth356=camProfileW} + lease, err := dualAcquire(ctx, l, r, "dual-active-wall-3d", map[string]int{l: leftWidth356, r: 640}, 6*time.Second, "dual webcam 3D wall self-calibration") if lease != nil { defer lease.stop() } @@ -1101,10 +1120,29 @@ func (a *app) dualAutoWallSelfCalibrate() { _ = writeFileAtomic(fitPath, jb) } - lease.stop() - <-lease.done + lease.stop() + <-lease.done + if result!=nil { + // UI cleanup is a barrier, not a queued promise, before another camera job. + valid356:=false + uiDone356:=a.studioOnUI(func(){ + a.presMu.Lock();identity356,identityErr356:=a.captureRenderIdentityLocked();a.presMu.Unlock() + a.clearCapturePresentation(presentation) + dualUI.Lock() + if dualUI.run==run { + dualUI.busy=false;dualUI.fitting=false;dualUI.lease=nil + if identityErr356==nil&&identity356==presentation.gate.identity&&ctx.Err()==nil&&!cameraCommandSuperseded(){ + dualUI.status="Dual capture complete. Detect will use this exact LEFT-camera photo." + valid356=true + }else{dualUI.status="Dual capture stopped: projector, project or command changed. Previous project kept."} + } + dualUI.Unlock() + }) + if uiDone356&&valid356 {capture356=&dualWorkflowCapture356{Room:room3D,Photo:litColorLeft,LeftID:l,RightID:r}} + return + } - a.ui(func() { + a.ui(func() { dualUI.Lock();currentRun:=dualUI.run==run;dualUI.Unlock() if !currentRun{return} a.presMu.Lock();currentIdentity,identityErr:=a.captureRenderIdentityLocked();a.presMu.Unlock() diff --git a/dual_install356_windows_test.go b/dual_install356_windows_test.go new file mode 100644 index 0000000..1188864 --- /dev/null +++ b/dual_install356_windows_test.go @@ -0,0 +1,37 @@ +//go:build windows + +package main + +import ( + "bytes" + "encoding/json" + "os" + "testing" +) + +func Test356DualCandidateSaveDoesNotActivateGlobalKnowledge(t *testing.T) { + old := objiqActive.Load() + defer objiqActive.Store(old) + sentinel := &objiqKnow{} + objiqSetActive(sentinel) + p := &Project{Name: "prior"} + raw, _ := json.Marshal(p) + if e := SaveDualDepthToProject(p, nil, nil, t.TempDir(), false); e == nil { + t.Fatal("invalid capture accepted") + } + after, _ := json.Marshal(p) + if !bytes.Equal(raw, after) || objiqActive.Load() != sentinel { + t.Fatal("failed serializer changed project or global IQ") + } +} +func Test356DualStopAndProjectEditGatePresent(t *testing.T) { + // Integration execution needs a native UI loop; the portable extracted + // production-method harness exercises the stopped/replaced/edit cases. + b, e := os.ReadFile("dual_capture_windows.go") + if e != nil { + t.Fatal(e) + } + if !bytes.Contains(b, []byte("identity356==presentation.gate.identity")) { + t.Fatal("final projector lifetime check missing") + } +} diff --git a/dual_source356.go b/dual_source356.go new file mode 100644 index 0000000..9707fd3 --- /dev/null +++ b/dual_source356.go @@ -0,0 +1,36 @@ +package main + +import ( + "bytes" + "fmt" + "image" +) + +// Same dimensions are not camera registration. This compares every decoded +// source pixel against the image owned by this specific stereo capture. +func compareCapturedPhoto356(path string, original image.Image, w, h int) error { + if original == nil { + return fmt.Errorf("missing real LEFT source") + } + b, e := depthReadBounded(path) + if e != nil { + return e + } + im, _, e := image.Decode(bytes.NewReader(b)) + if e != nil { + return e + } + if original.Bounds().Dx() != w || original.Bounds().Dy() != h || im.Bounds().Dx() != w || im.Bounds().Dy() != h { + return fmt.Errorf("captured LEFT geometry changed") + } + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + r, g, b, a := im.At(x+im.Bounds().Min.X, y+im.Bounds().Min.Y).RGBA() + rr, gg, bb, aa := original.At(x+original.Bounds().Min.X, y+original.Bounds().Min.Y).RGBA() + if r != rr || g != gg || b != bb || a != aa { + return fmt.Errorf("Detect source no longer equals captured LEFT pixels") + } + } + } + return nil +} diff --git a/dual_source356_test.go b/dual_source356_test.go new file mode 100644 index 0000000..82aecb4 --- /dev/null +++ b/dual_source356_test.go @@ -0,0 +1,49 @@ +package main + +import ( + "image" + "image/color" + "image/png" + "os" + "path/filepath" + "testing" +) + +func Test356CapturePhotoRejectsSameSizeDifferentCamera(t *testing.T) { + original := image.NewNRGBA(image.Rect(0, 0, 8, 6)) + for y := 0; y < 6; y++ { + for x := 0; x < 8; x++ { + original.Set(x, y, color.NRGBA{R: uint8(x * 25), G: uint8(y * 30), A: 255}) + } + } + path := filepath.Join(t.TempDir(), "left.png") + save := func(im image.Image) { + f, e := os.Create(path) + if e != nil { + t.Fatal(e) + } + if e = png.Encode(f, im); e != nil { + t.Fatal(e) + } + if e = f.Close(); e != nil { + t.Fatal(e) + } + } + save(original) + if e := compareCapturedPhoto356(path, original, 8, 6); e != nil { + t.Fatal(e) + } + if e := compareCapturedPhoto356(path, original, 6, 8); e == nil { + t.Fatal("changed dimensions accepted") + } + changed := image.NewNRGBA(image.Rect(0, 0, 8, 6)) + copy(changed.Pix, original.Pix) + changed.Set(7, 5, color.NRGBA{B: 255, A: 255}) + save(changed) + if e := compareCapturedPhoto356(path, original, 8, 6); e == nil { + t.Fatal("same-size wrong-camera/photo accepted") + } + if e := compareCapturedPhoto356(path, nil, 8, 6); e == nil { + t.Fatal("missing real capture accepted") + } +} diff --git a/dual_stereo_depth.go b/dual_stereo_depth.go index c2ec821..ec71ccc 100644 --- a/dual_stereo_depth.go +++ b/dual_stereo_depth.go @@ -12,6 +12,7 @@ import ( "os" "path/filepath" "sort" + "strings" "time" ) @@ -1389,7 +1390,17 @@ func EncodeNormalsPNG(normals []float32, w, h int) ([]byte, error) { // surface normals, wall-plane-isolated projector calibration, T3Rig, cryptographic // SHA-256 staging receipts (required by Renderer.projectDepth), and live ObjectIQ // knowledge onto Project p inside outDir! -func SaveDualDepthToProject(p *Project, res *DualRoom3DResult, sourcePhoto image.Image, outDir string, installWallMap bool) error { +// Project publication is transactional: a failed write must not partially +// replace the caller's calibration/depth references. +func SaveDualDepthToProject(p *Project,res *DualRoom3DResult,sourcePhoto image.Image,outDir string,installWallMap bool)error{ + if p==nil{return errors.New("missing project")} + raw,e:=json.Marshal(p);if e!=nil{return e} + var candidate Project;if e=json.Unmarshal(raw,&candidate);e!=nil{return e} + if e=saveDualDepthCandidate355(&candidate,res,sourcePhoto,outDir,installWallMap);e!=nil{return e} + *p=candidate + return nil +} +func saveDualDepthCandidate355(p *Project, res *DualRoom3DResult, sourcePhoto image.Image, outDir string, installWallMap bool) error { if p == nil || res == nil || res.Depth == nil || !res.Depth.validShape() { return errors.New("missing project or 3D depth result") } @@ -1397,20 +1408,15 @@ func SaveDualDepthToProject(p *Project, res *DualRoom3DResult, sourcePhoto image return err } - // Ensure sourcePhoto exists and matches p.Scene.W x p.Scene.H so Renderer.projectDepth() passes! - if sourcePhoto == nil { - w, h := p.Scene.W, p.Scene.H - if w <= 0 || h <= 0 { - w, h = res.Depth.W, res.Depth.H - } - im := image.NewNRGBA(image.Rect(0, 0, w, h)) - for y := 0; y < h; y++ { - for x := 0; x < w; x++ { - im.SetNRGBA(x, y, color.NRGBA{R: 128, G: 128, B: 128, A: 255}) - } - } - sourcePhoto = im - } + // A missing real source cannot establish camera/photo alignment. Never synthesize it. + if sourcePhoto==nil{return errors.New("real left-camera source photo is required; synthetic photo cannot bind room depth")} + if res.Rig==nil{return errors.New("depth rig provenance missing")} + if res.Rig.ScaleSource!="given-distance"&&res.Rig.ScaleSource!="assumed-stereo-baseline"{return errors.New("depth scale provenance missing")} + if len(res.MetricZMeters)!=res.Depth.W*res.Depth.H{return errors.New("actual metric camera-Z samples missing")} + if sourcePhoto.Bounds().Dx()!=res.Rig.LeftW||sourcePhoto.Bounds().Dy()!=res.Rig.LeftH{return errors.New("left-camera source photo dimensions do not match captured rig")} + // Validate the full sample buffer before any project fields or owned files change. + if _,e:=encodeMetricRoom355(res.MetricZMeters,res.Depth.Valid,res.Depth.W,res.Depth.H,res.Rig.ScaleSource,strings.Repeat("0",64),strings.Repeat("0",64));e!=nil{return e} + sb := sourcePhoto.Bounds() p.Scene.W, p.Scene.H = sb.Dx(), sb.Dy() @@ -1440,17 +1446,17 @@ func SaveDualDepthToProject(p *Project, res *DualRoom3DResult, sourcePhoto image return err } - normalsPath := "" - if normBytes, nerr := EncodeNormalsPNG(res.Normals, res.Depth.W, res.Depth.H); nerr == nil { - normalsPath = filepath.Join(outDir, "dual-3d-normals.png") - _ = writeFileAtomic(normalsPath, normBytes) - } + normalsPath := "" + if len(res.Normals)>0 { + normBytes,nerr:=EncodeNormalsPNG(res.Normals,res.Depth.W,res.Depth.H);if nerr!=nil{return nerr} + normalsPath=filepath.Join(outDir,"dual-3d-normals.png") + if nerr=writeFileAtomic(normalsPath,normBytes);nerr!=nil{return nerr} + } - if res.Rig != nil { - if rigBytes, rerr := json.MarshalIndent(res.Rig, "", " "); rerr == nil { - _ = writeFileAtomic(filepath.Join(outDir, "dual-trinocular-rig.json"), rigBytes) - } - } + if res.Rig!=nil { + rigBytes,rerr:=json.MarshalIndent(res.Rig,""," ");if rerr!=nil{return rerr} + if rerr=writeFileAtomic(filepath.Join(outDir,"dual-trinocular-rig.json"),rigBytes);rerr!=nil{return rerr} + } // Install parallax-free wall-plane projector calibration when requested and valid. if installWallMap && res.Rig != nil && len(res.Rig.WallPairs) >= 6 && saneQuad(res.Rig.WallH) { @@ -1474,7 +1480,8 @@ func SaveDualDepthToProject(p *Project, res *DualRoom3DResult, sourcePhoto image units = "relative-meters (stereo baseline)" } p.DepthMetric = &DepthMetricRef{ - File: depthPath, + // Normalized depthPath is never a metric PNG. Legacy consumers abstain. + File: "", Normals: normalsPath, Variant: "dual-webcam-trinocular-3d", Units: units, @@ -1485,7 +1492,16 @@ func SaveDualDepthToProject(p *Project, res *DualRoom3DResult, sourcePhoto image } // Compute AuthoringSHA256 AFTER p.Map, p.Surfaces, p.Scene, and p.T3Rig are finalized! - authSHA := depthAuthoringSHA(p) + authSHA := depthAuthoringSHA(p) + metricBytes,metricErr:=encodeMetricRoom355(res.MetricZMeters,res.Depth.Valid,res.Depth.W,res.Depth.H,res.Rig.ScaleSource,depthSHA(stagedBytes),authSHA) + if metricErr!=nil{return metricErr} + metricPath:=filepath.Join(outDir,"dual-3d-camera-z355.json") + if metricErr=writeFileAtomic(metricPath,metricBytes);metricErr!=nil{return metricErr} + p.DepthMetric.MetricZFile=metricPath + p.DepthMetric.MetricZSHA256=depthSHA(metricBytes) + p.DepthMetric.SourceSHA256=depthSHA(stagedBytes) + p.DepthMetric.AuthoringSHA256=authSHA + p.DepthMetric.ScaleSource=res.Rig.ScaleSource p.Depth = &DepthRef{ AuthoringSHA256: authSHA, Alignment: "dual-stereo-left-camera", @@ -1503,22 +1519,7 @@ func SaveDualDepthToProject(p *Project, res *DualRoom3DResult, sourcePhoto image Device: "dual-webcam-native-go", } - // Activate live ObjectIQ 3D relief + surface normals for Carbon, Chimera, Muse & Living Objects! - know := objiqBuild(objiqInputs{ - Photo: sourcePhoto, - PhotoHash: depthSHA(stagedBytes), - Aspect: float64(p.Scene.W) / float64(maxi(1, p.Scene.H)), - Surfaces: p.Surfaces, - RelDepth: res.Depth, - RelSrc: "dual-webcam-trinocular-3d", - MetricMM: res.MetricMM, - MW: res.Depth.W, - MH: res.Depth.H, - Normals: res.Normals, - NW: res.Depth.W, - NH: res.Depth.H, - }) - objiqSetActive(know) + // Caller activates ObjectIQ only after its accepted project commit. return nil } diff --git a/dual_workflow356_policy_test.go b/dual_workflow356_policy_test.go new file mode 100644 index 0000000..d9d515d --- /dev/null +++ b/dual_workflow356_policy_test.go @@ -0,0 +1,45 @@ +package main + +import ( + "os" + "strings" + "testing" +) + +// Wiring checks complement the executable source/save tests. They are not +// hardware evidence and must never be described as capture execution. +func Test356DualTransactionWiring(t *testing.T) { + read := func(name string) string { + b, e := os.ReadFile(name) + if e != nil { + t.Fatal(e) + } + return string(b) + } + det := read("detect.go") + install := strings.Index(det, "dualDir:=filepath.Join") + if install < 0 { + t.Fatal("dual candidate install missing") + } + save := strings.Index(det[install:], "if err := p.save(out)") + if save < 0 { + t.Fatal("dual candidate not serialized before accepted Detect save") + } + if !strings.Contains(det, "(handoff==nil||handoff.dual356==nil) && cloud") { + t.Fatal("paid fallback must not be possible in the dual workflow") + } + workflow := read("dual_workflow356_windows.go") + for _, gate := range []string{"compareCapturedPhoto356", "calibrationOwnerCommitCurrent", "bytes.Equal(raw, current356)", "capture.Photo.Bounds().Dx() != source.resolution[0]"} { + if !strings.Contains(workflow, gate) { + t.Fatal("missing source/publication gate", gate) + } + } + if strings.Contains(read("dual_stereo_depth.go"), "objiqSetActive(") { + t.Fatal("candidate serializer may not mutate global room knowledge") + } + capture := read("dual_capture_windows.go") + stop := strings.Index(capture, "if result!=nil {\n // UI cleanup") + if stop < 0 || !strings.Contains(capture[:stop], "<-lease.done") { + t.Fatal("capture-only result before driver cleanup barrier") + } +} diff --git a/dual_workflow356_windows.go b/dual_workflow356_windows.go new file mode 100644 index 0000000..acbacad --- /dev/null +++ b/dual_workflow356_windows.go @@ -0,0 +1,269 @@ +//go:build windows + +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "image/png" + "os" + "path/filepath" + "time" +) + +type dualDetectSource356 struct { + capture *dualWorkflowCapture356 + path, hash, camera string + resolution [2]int +} + +func (d *dualDetectSource356) verifyPhoto356(path string, w, h int) error { + if d == nil || d.capture == nil || d.capture.Room == nil { + return fmt.Errorf("missing owned dual capture") + } + if w != d.resolution[0] || h != d.resolution[1] { + return fmt.Errorf("captured LEFT dimensions changed") + } + return compareCapturedPhoto356(path, d.capture.Photo, w, h) +} +func (a *app) dualWorkflowAvailable356() bool { + _, infos := U.camSnapshot() + ids := map[string]bool{} + for _, v := range infos { + if id := parseCameraID(v.SymLink); id != "" { + ids[id] = true + } + } + return len(ids) >= 2 +} + +// Called within the serialized camera command, before any destructive fresh reset. +func (a *app) dualFreshPrep356() (*calibrationOwner, *dualDetectSource356) { + source := a.calibrationOwnerSnapshot() + if source == nil { + return nil, nil + } + if why := a.hcRestoreGate(); why != "" { + logf("Dual workflow stopped: recovery must finish first: %s", why) + return nil, nil + } + labels, infos := U.camSnapshot() + dualUI.Lock() + left, right := dualUI.left, dualUI.right + if left < 0 || right < 0 || left >= len(infos) || right >= len(infos) || left == right { + left = -1 + right = -1 + // Keep the user's selected camera canonical whenever two-camera roles need defaults. + for i, v := range infos { + if parseCameraID(v.SymLink) == camActiveID() { + left = i + break + } + } + if left < 0 && len(infos) > 0 { + left = 0 + } + for i, v := range infos { + if i != left && left >= 0 && parseCameraID(v.SymLink) != parseCameraID(infos[left].SymLink) { + right = i + break + } + } + dualUI.left, dualUI.right = left, right + } + dualUI.Unlock() + if left < 0 || right < 0 || left >= len(labels) || right >= len(labels) { + logf("Dual workflow needs two distinct connected camera identities. Previous project kept.") + return nil, nil + } + // No setCamera(): it queues another command and would supersede this workflow. + selection356 := false + if !a.studioOnUI(func() { + if !a.calibrationOwnerCurrent(source) { + return + } + stopCamera() + U.camSel = left + a.st.Camera = labels[left] + a.st.CameraID = parseCameraID(infos[left].SymLink) + a.applyCameraSel() + selection356 = true + }) || !selection356 { + return nil, nil + } + if source.epoch != calibrationStopEpoch.Load() || source.ticket != cameraCommandWanted.Load() { + return nil, nil + } + if a.pl != source.player || a.cur.Path != source.path || a.pl.P != source.project { + return nil, nil + } + a.cameraTest() + if cameraCommandSuperseded() || !U.cam { + return nil, nil + } + source = a.calibrationOwnerSnapshot() + if source == nil { + return nil, nil + } + result := make(chan *dualWorkflowCapture356, 1) + if !a.studioOnUI(func() { a.dualAutoWallSelfCalibrate356(result) }) { + return nil, nil + } + capture := <-result + a.studioOnUI(func() {}) // Flush error/presentation cleanup before another owner is considered. + if capture == nil || !a.calibrationOwnerCurrent(source) { + logf("Dual workflow stopped before Detect. Previous project was not reset.") + return nil, nil + } + if capture.Photo.Bounds().Dx() != source.resolution[0] || capture.Photo.Bounds().Dy() != source.resolution[1] { + logf("Dual workflow stopped: independent LEFT mode differs from selected calibration mode. Previous project kept.") + return nil, nil + } + var photo bytes.Buffer + if e := png.Encode(&photo, capture.Photo); e != nil { + return nil, nil + } + dir := filepath.Join(dataDir, "projects", "dual3d", fmt.Sprintf("workflow-%d", time.Now().UnixNano())) + if e := os.MkdirAll(dir, 0700); e != nil { + logf("Dual source folder: %v", e) + return nil, nil + } + path := filepath.Join(dir, "canonical-left.png") + if e := writeFileAtomic(path, photo.Bytes()); e != nil { + logf("Dual source save: %v", e) + return nil, nil + } + d := &dualDetectSource356{capture: capture, path: path, hash: depthSHA(photo.Bytes()), camera: labels[left], resolution: [2]int{capture.Photo.Bounds().Dx(), capture.Photo.Bounds().Dy()}} + for _, room := range autoDetectModes(a.st.Indoor) { + h := &autoDetectHandoff{source: source, dual356: d} + a.detectModeHandoff(false, room, "local", nil, h) // Never take a paid-provider fallback. + if !a.studioOnUI(func() {}) { + return nil, nil + } + h.mu.Lock() + next := h.result + h.mu.Unlock() + if next != nil && a.calibrationOwnerCurrent(next) { + a.studioOnUI(func() { a.dualActivateKnowledge356(next, d) }) + return next, d + } + if !a.calibrationOwnerCurrent(source) { + return nil, nil + } + } + logf("Dual capture saved locally, but Detect produced no accepted source-bound outlines. Previous calibration was not reset.") + return nil, nil +} +func (a *app) dualInstallOwned356(owner *calibrationOwner, d *dualDetectSource356, wall bool) bool { + if d == nil || !a.calibrationOwnerCurrent(owner) { + return false + } + owner.player.mu.Lock() + raw, e := json.Marshal(owner.project) + owner.player.mu.Unlock() + if e != nil { + return false + } + var candidate Project + if e = json.Unmarshal(raw, &candidate); e != nil { + return false + } + if depthAuthoringSHA(&candidate) != owner.authoring { + return false + } + // The accepted Detect project's photo must still be the exact captured LEFT pixels. + photo := stringsTrimProjectPhoto356(owner.path) + if e = d.verifyPhoto356(photo, candidate.Scene.W, candidate.Scene.H); e != nil { + logf("Dual install stopped: %v", e) + return false + } + candidate.PhotoCam = d.camera + out := filepath.Join(filepath.Dir(d.path), fmt.Sprintf("depth-%d", time.Now().UnixNano())) + res356 := *d.capture.Room + rig356 := *res356.Rig + if !wall && candidate.T3Rig != nil { + rig356.RigLeftProj = candidate.T3Rig + } + res356.Rig = &rig356 + if e = SaveDualDepthToProject(&candidate, &res356, d.capture.Photo, out, wall && !hasProtectedMap(candidate.Map)); e != nil { + logf("Dual install stopped: %v", e) + return false + } + installed := false + a.studioOnUI(func() { + a.studioContextMu.Lock() + defer a.studioContextMu.Unlock() + owner.player.mu.Lock() + defer owner.player.mu.Unlock() + calibrationMutationMu.Lock() + defer calibrationMutationMu.Unlock() + if !a.calibrationOwnerCommitCurrent(owner) { + return + } + // Measurement ownership excludes scene/effect choices. Do not overwrite one + // the user edited while candidate files were being prepared. + current356, err356 := json.Marshal(owner.project) + if err356 != nil || !bytes.Equal(raw, current356) { + logf("Dual depth save stopped: project settings changed during preparation.") + return + } + backup := filepath.Join(filepath.Dir(d.path), fmt.Sprintf("before-install-%d.json", time.Now().UnixNano())) + prior, err := json.Marshal(owner.project) + if err != nil { + return + } + if err = writeFileAtomic(backup, prior); err != nil { + return + } + if err = candidate.save(owner.path); err != nil { + logf("Dual project save failed: %v", err) + return + } + *owner.project = candidate + owner.player.R.invalidate() + owner.authoring = depthAuthoringSHA(owner.project) + a.dualActivateKnowledgeLocked356(owner, d) + installed = true + }) + if installed { + logf("Dual workflow: exact captured LEFT photo, new outlines, depth, normals and actual camera-Z payload saved together. Scale: %s; not independently verified metric distance.", d.capture.Room.Rig.ScaleSource) + } + return installed +} +func stringsTrimProjectPhoto356(path string) string { + return path[:len(path)-len(filepath.Ext(path))] + ".photo.jpg" +} + +// Global room knowledge is activated only after accepted publication, never by +// a candidate serializer. No stale worker may change a different project's IQ. +func (a *app) dualActivateKnowledge356(o *calibrationOwner, d *dualDetectSource356) { + if !a.calibrationOwnerCurrent(o) { + return + } + o.player.mu.Lock() + defer o.player.mu.Unlock() + calibrationMutationMu.Lock() + defer calibrationMutationMu.Unlock() + if !a.calibrationOwnerCommitCurrent(o) { + return + } + a.dualActivateKnowledgeLocked356(o, d) +} +func (a *app) dualActivateKnowledgeLocked356(o *calibrationOwner, d *dualDetectSource356) { + res := d.capture.Room + p := o.project + k := objiqBuild(objiqInputs{Photo: d.capture.Photo, PhotoHash: p.Depth.SourceSHA256[:16], Aspect: float64(p.Scene.W) / float64(maxi(1, p.Scene.H)), Surfaces: p.Surfaces, RelDepth: res.Depth, RelSrc: "dual-webcam-trinocular-3d", MetricMM: res.MetricMM, MW: res.Depth.W, MH: res.Depth.H, Normals: res.Normals, NW: res.Depth.W, NH: res.Depth.H}) + k.ProjectPath = o.path + objiqSetActive(k) + o.player.R.prepareLearnedObjects() +} + +func (a *app) dualDepthNeedsPair356() bool { + if a.pl == nil { + return false + } + a.pl.mu.Lock() + defer a.pl.mu.Unlock() + return a.pl.P != nil && a.pl.P.Depth != nil && a.pl.P.Depth.Alignment == "dual-stereo-left-camera" +} diff --git a/metric_room355.go b/metric_room355.go new file mode 100644 index 0000000..031abc2 --- /dev/null +++ b/metric_room355.go @@ -0,0 +1,62 @@ +package main + +import ( + "encoding/hex" + "encoding/json" + "errors" + "math" +) + +// The normalized relative PNG cannot be decoded into metres. This versioned +// payload preserves the reconstructed camera-Z values and their real scale +// provenance, separately from the existing relative-depth lighting image. +type metricRoomPayload355 struct { + Schema string `json:"schema"` + W, H int + Units string `json:"units"` + ScaleSource string `json:"scale_source"` + SourceSHA256 string `json:"source_sha256"` + AuthoringSHA256 string `json:"authoring_sha256"` + Z []float32 `json:"camera_z_metres"` + Valid []bool `json:"valid"` +} + +func encodeMetricRoom355(z []float32, valid []bool, w, h int, scale, source, authoring string) ([]byte, error) { + if w < 1 || h < 1 || w > 4096 || h > 4096 || w > int(^uint(0)>>1)/h || len(z) != w*h || len(valid) != w*h { + return nil, errors.New("metric depth dimensions do not match") + } + _, sourceErr := hex.DecodeString(source) + _, authoringErr := hex.DecodeString(authoring) + if len(source) != 64 || len(authoring) != 64 || sourceErr != nil || authoringErr != nil { + return nil, errors.New("metric depth source receipts missing") + } + if scale != "given-distance" && scale != "assumed-stereo-baseline" { + return nil, errors.New("metric scale provenance missing") + } + p := metricRoomPayload355{Schema: "projection-mapper-camera-z355", W: w, H: h, Units: "metres", ScaleSource: scale, SourceSHA256: source, AuthoringSHA256: authoring, Z: make([]float32, len(z)), Valid: append([]bool(nil), valid...)} + count := 0 + for i, v := range z { + if !valid[i] { + continue + } + if math.IsNaN(float64(v)) || math.IsInf(float64(v), 0) || v <= 0 || v > 1000 { + return nil, errors.New("invalid valid metric depth sample") + } + p.Z[i] = v + count++ + } + if count == 0 { + return nil, errors.New("no valid metric depth samples") + } + return json.Marshal(p) +} +func decodeMetricRoom355(raw []byte) (metricRoomPayload355, error) { + var p metricRoomPayload355 + if json.Unmarshal(raw, &p) != nil || p.Schema != "projection-mapper-camera-z355" || p.Units != "metres" { + return p, errors.New("unsupported metric depth format") + } + if _, e := encodeMetricRoom355(p.Z, p.Valid, p.W, p.H, p.ScaleSource, p.SourceSHA256, p.AuthoringSHA256); e != nil { + return p, e + } + return p, nil +} diff --git a/metric_room355_test.go b/metric_room355_test.go new file mode 100644 index 0000000..2e06340 --- /dev/null +++ b/metric_room355_test.go @@ -0,0 +1,51 @@ +package main + +import ( + "math" + "strings" + "testing" +) + +func Test355MetricRoundTripKeepsMetresAndValidity(t *testing.T) { + for _, scale := range []string{"given-distance", "assumed-stereo-baseline"} { + z := []float32{1.725, 2.83, 3.205, 0} + valid := []bool{true, true, true, false} + raw, e := encodeMetricRoom355(z, valid, 2, 2, scale, strings.Repeat("a", 64), strings.Repeat("b", 64)) + if e != nil { + t.Fatal(e) + } + p, e := decodeMetricRoom355(raw) + if e != nil { + t.Fatal(e) + } + if p.Z[0] != z[0] || p.Z[2] != z[2] || p.Valid[3] || p.Units != "metres" || p.ScaleSource != scale { + t.Fatal("depth units or provenance changed", p) + } + p.Z[0] = 99 + if z[0] != 1.725 { + t.Fatal("input aliases payload") + } + } +} +func Test355MetricRejectsInvalidSamplesAndMissingReceipts(t *testing.T) { + s := strings.Repeat("a", 64) + for _, v := range []float32{0, -1, float32(math.NaN()), float32(math.Inf(1)), 1001} { + if _, e := encodeMetricRoom355([]float32{v}, []bool{true}, 1, 1, "given-distance", s, s); e == nil { + t.Fatal("invalid depth accepted", v) + } + } + for _, scale := range []string{"", "stereo-metric-locked", "manual"} { + if _, e := encodeMetricRoom355([]float32{2}, []bool{true}, 1, 1, scale, s, s); e == nil { + t.Fatal("unknown scale accepted") + } + } + if _, e := encodeMetricRoom355([]float32{2}, []bool{true}, 1, 1, "given-distance", "", s); e == nil { + t.Fatal("source missing") + } + if _, e := encodeMetricRoom355([]float32{2}, []bool{false}, 1, 1, "given-distance", s, s); e == nil { + t.Fatal("all invalid accepted") + } + if _, e := decodeMetricRoom355([]byte("not a metric payload")); e == nil { + t.Fatal("arbitrary bytes accepted") + } +} diff --git a/metric_room_binding355.go b/metric_room_binding355.go new file mode 100644 index 0000000..e4f5564 --- /dev/null +++ b/metric_room_binding355.go @@ -0,0 +1,65 @@ +package main + +import ( + "errors" + "math" +) + +// Consumers must pass the current immutable render-plan lineage. A legacy +// model PNG or normalized relative-depth image is never a metric room volume. +func (r *Renderer) measuredMetricRoom355(plans []*plan) (metricRoomPayload355, error) { + var none metricRoomPayload355 + if r == nil || r.P == nil || r.P.Depth == nil || r.P.DepthMetric == nil { + return none, errors.New("no receipt-bound metric room capture") + } + p := r.P + d, m := p.Depth, p.DepthMetric + if p.Map.BadCal || p.UncalibratedShow || d.Alignment != "dual-stereo-left-camera" || d.Variant != "dual-webcam-trinocular-3d" { + return none, errors.New("metric room alignment is not verified") + } + if m.ScaleSource != "given-distance" || m.MetricZFile == "" || len(m.MetricZSHA256) != 64 { + return none, errors.New("metric scale was not measured or payload is missing") + } + auth := depthAuthoringSHA(p) + if auth == "" || auth != d.AuthoringSHA256 || auth != m.AuthoringSHA256 || m.SourceSHA256 != d.SourceSHA256 { + return none, errors.New("metric room authoring source changed") + } + if len(plans) == 0 { + return none, errors.New("no current plan lineage") + } + for _, pl := range plans { + if pl == nil || !pl.photoScene || pl.t3 != nil || pl.depthAuthoring != auth { + return none, errors.New("metric camera-to-photo mapping is unsupported") + } + } + rig := p.T3Rig + if rig == nil || rig.Flat || rig.Quality() != "MEASURED" || !t3Finite(rig.RMSProj) || rig.RMSProj > t3OKRMS || rig.Cam.F <= 0 || rig.CamW != d.SourceW || rig.CamH != d.SourceH { + return none, errors.New("metric camera/projector rig is not measured and accurate") + } + if r.projectDepth() == nil { + return none, errors.New("metric source photo or relative depth receipt failed") + } + raw, e := depthReadBounded(m.MetricZFile) + if e != nil || depthSHA(raw) != m.MetricZSHA256 { + return none, errors.New("metric payload bytes changed") + } + payload, e := decodeMetricRoom355(raw) + if e != nil { + return none, e + } + if payload.AuthoringSHA256 != auth || payload.SourceSHA256 != d.SourceSHA256 || payload.ScaleSource != m.ScaleSource || payload.W != m.IW || payload.H != m.IH { + return none, errors.New("metric payload receipts disagree") + } + return payload, nil +} + +// Camera-Z ordering only. Unknown pixels abstain, never act like far space. +func (p *metricRoomPayload355) zAt(u, v float64) (float64, bool) { + if p == nil || p.W < 1 || p.H < 1 || len(p.Z) != p.W*p.H || len(p.Valid) != len(p.Z) || math.IsNaN(u+v) || math.IsInf(u+v, 0) || u < 0 || v < 0 || u > 1 || v > 1 { + return 0, false + } + x, y := mini(p.W-1, int(u*float64(p.W))), mini(p.H-1, int(v*float64(p.H))) + i := y*p.W + x + z := float64(p.Z[i]) + return z, p.Valid[i] && z > 0 && !math.IsNaN(z) && !math.IsInf(z, 0) +} diff --git a/metric_room_binding355_test.go b/metric_room_binding355_test.go new file mode 100644 index 0000000..0f2fcd1 --- /dev/null +++ b/metric_room_binding355_test.go @@ -0,0 +1,116 @@ +package main + +import ( + "bytes" + "encoding/json" + "image" + "image/color" + "os" + "path/filepath" + "testing" +) + +func Test355SaveRejectsMissingRealSourceWithoutProjectMutation(t *testing.T) { + p := &Project{Name: "untouched"} + raw, _ := json.Marshal(p) + res := &DualRoom3DResult{Depth: &depthMap{W: 1, H: 1, V: []float32{.5}, Valid: []bool{true}}} + if e := SaveDualDepthToProject(p, res, nil, t.TempDir(), false); e == nil { + t.Fatal("synthetic source accepted") + } + after, _ := json.Marshal(p) + if !bytes.Equal(raw, after) { + t.Fatal("rejected capture changed project") + } +} +func Test355SavedMetricDataIsNotRelativePNG(t *testing.T) { + p := &Project{} + dm := &depthMap{W: 2, H: 2, V: []float32{0, .3, .8, 1}, Valid: []bool{true, true, true, true}} + res := &DualRoom3DResult{Depth: dm, MetricZMeters: []float32{1.7, 2.3, 3.1, 3.5}, MetricMM: []float32{1700, 2300, 3100, 3500}, Rig: &DualStereoRig{ScaleSource: "assumed-stereo-baseline", LeftW: 4, LeftH: 4}} + src := image.NewRGBA(image.Rect(0, 0, 4, 4)) + for y := 0; y < 4; y++ { + for x := 0; x < 4; x++ { + src.Set(x, y, color.RGBA{R: uint8(x * 40), G: uint8(y * 40), B: 80, A: 255}) + } + } + old := objiqActive.Load() + defer objiqActive.Store(old) + if e := SaveDualDepthToProject(p, res, src, t.TempDir(), false); e != nil { + t.Fatal(e) + } + m := p.DepthMetric + if m.File != "" || m.MetricZFile == "" || m.MetricZFile == p.Depth.File { + t.Fatal("relative PNG still labeled metric", m) + } + raw, e := depthReadBounded(m.MetricZFile) + if e != nil { + t.Fatal(e) + } + z, e := decodeMetricRoom355(raw) + if e != nil { + t.Fatal(e) + } + if z.Z[0] != 1.7 || z.Z[3] != 3.5 || z.ScaleSource != "assumed-stereo-baseline" || depthSHA(raw) != m.MetricZSHA256 { + t.Fatal("real metric samples or scale receipt lost") + } + if _, e := (&Renderer{P: p}).measuredMetricRoom355(nil); e == nil { + t.Fatal("assumed scale accepted as measured") + } +} +func Test355MetricUnknownPixelAbstains(t *testing.T) { + p := metricRoomPayload355{W: 2, H: 1, Z: []float32{2, 0}, Valid: []bool{true, false}} + if z, ok := p.zAt(.1, .5); !ok || z != 2 { + t.Fatal("valid depth lost") + } + if _, ok := p.zAt(.8, .5); ok { + t.Fatal("unknown treated as far") + } +} + +func Test355SaveRejectsMismatchedCameraPhotoBeforeMutation(t *testing.T) { + p := &Project{Name: "untouched"} + before, _ := json.Marshal(p) + res := &DualRoom3DResult{Depth: &depthMap{W: 1, H: 1, V: []float32{.5}, Valid: []bool{true}}, MetricZMeters: []float32{2}, Rig: &DualStereoRig{ScaleSource: "given-distance", LeftW: 320, LeftH: 180}} + if e := SaveDualDepthToProject(p, res, image.NewRGBA(image.Rect(0, 0, 10, 10)), t.TempDir(), false); e == nil { + t.Fatal("unregistered camera photo size accepted") + } + after, _ := json.Marshal(p) + if !bytes.Equal(before, after) { + t.Fatal("rejected source changed project") + } +} + +func Test355FailedMetricWritePreservesCallerProject(t *testing.T) { + p := &Project{Name: "untouched"} + before, _ := json.Marshal(p) + dm := &depthMap{W: 1, H: 1, V: []float32{.5}, Valid: []bool{true}} + res := &DualRoom3DResult{Depth: dm, MetricZMeters: []float32{2}, Rig: &DualStereoRig{ScaleSource: "given-distance", LeftW: 2, LeftH: 2}} + dir := t.TempDir() + if e := os.Mkdir(filepath.Join(dir, "dual-3d-camera-z355.json"), 0700); e != nil { + t.Fatal(e) + } + if e := SaveDualDepthToProject(p, res, image.NewRGBA(image.Rect(0, 0, 2, 2)), dir, false); e == nil { + t.Fatal("metric write unexpectedly succeeded") + } + after, _ := json.Marshal(p) + if !bytes.Equal(before, after) { + t.Fatal("failed write partially changed project") + } +} + +func Test356FailedNormalsWritePreservesCallerProject(t *testing.T) { + p := &Project{Name: "untouched"} + before, _ := json.Marshal(p) + dm := &depthMap{W: 1, H: 1, V: []float32{.5}, Valid: []bool{true}} + res := &DualRoom3DResult{Depth: dm, MetricZMeters: []float32{2}, Normals: []float32{0, 0, -1}, Rig: &DualStereoRig{ScaleSource: "assumed-stereo-baseline", LeftW: 2, LeftH: 2}} + dir := t.TempDir() + if e := os.Mkdir(filepath.Join(dir, "dual-3d-normals.png"), 0700); e != nil { + t.Fatal(e) + } + if e := SaveDualDepthToProject(p, res, image.NewRGBA(image.Rect(0, 0, 2, 2)), dir, false); e == nil { + t.Fatal("failed normals write accepted") + } + after, _ := json.Marshal(p) + if !bytes.Equal(before, after) { + t.Fatal("failed normals save changed project") + } +} diff --git a/project.go b/project.go index 0983c89..f4a2e21 100644 --- a/project.go +++ b/project.go @@ -93,6 +93,13 @@ type ScanRef struct { } type DepthMetricRef struct { + //355: exact camera-Z payload. File remains reserved for the legacy model PNG. + MetricZFile string `json:"metric_z_file,omitempty"` + MetricZSHA256 string `json:"metric_z_sha256,omitempty"` + SourceSHA256 string `json:"source_sha256,omitempty"` + AuthoringSHA256 string `json:"authoring_sha256,omitempty"` + ScaleSource string `json:"scale_source,omitempty"` + File string `json:"file"` Normals string `json:"normals,omitempty"` Variant string `json:"variant"` diff --git a/whatsnew_ui_win.go b/whatsnew_ui_win.go index b7e5909..01bb987 100644 --- a/whatsnew_ui_win.go +++ b/whatsnew_ui_win.go @@ -47,6 +47,7 @@ type whatsNewFeature struct { } var whatsNewFeatures = []whatsNewFeature{ + {"356: Source-bound dual Auto and Quick", "Experimental. Native Windows, two-camera/projector and physical accuracy tests NOT RUN.", []string{"Auto and Quick use a serialized two-webcam capture when two distinct devices are connected. Detect uses the exact captured LEFT photo. The old project is not reset before capture and a usable accepted Detect handoff.", "New outlines, relative depth, normals and actual camera-Z payload are saved together. Candidate saves do not activate global room knowledge before accepted publication. Existing dual data is not discarded for a single-camera reset when the second camera is absent.", "Stereo scale still assumes 0.25m camera spacing. Saved camera-Z is baseline-scaled, not independently measured metric truth. Eligible depth consumers use valid saved depth; not every effect/calibration consumes both cameras."}, []string{"Back up projects and test Auto, Quick, Stop, camera disconnect and project switching. Local Detect only on this route; no paid-provider fallback. 355 retained.", "Software checks are not physical acceptance. The final independent map check can still project markers on furniture; flat-only dot placement is NOT certified."}, ""}, {"353: Preview follows selection while the saved show is paused", "Experimental. Native Windows and projector execution NOT RUN. Dual-webcam first-pattern timeout remains unresolved.", []string{"A paused saved-show clock does not turn off temporary preview output. Shared Previous, Next and filtered dropdown now refresh an already-active owned preview in that state without resuming the show.", "Stop, blackout, inactive/foreign preview and calibration guards remain."}, []string{"With the saved show paused, start a temporary preview and use Next/Previous. Stop it, browse again and confirm it stays stopped. Native execution remains unverified."}, ""}, {"352: Shared effect preview follows Previous and Next", "Experimental. Native Windows and projector tests NOT RUN. Dual-webcam first-pattern timeout remains unresolved.", []string{"Shared catalog Previous, Next and effect-picker selection now refresh an already-active temporary preview instead of only changing the selected label.", "Stopped, inactive and foreign previews are not started or replaced by browsing. Selection restoration stays metadata-only; no scene is saved.", "Scene-preview libraries tag their previews by tab so shared browsing can follow the correct owner."}, []string{"Start a preview, press Next and Previous, then Stop and browse again. The stopped show must remain stopped. No native execution claim from compile-only tests."}, ""}, {"351: Guided calibration handoff and usable outline canvas", "Experimental. Full Windows app and real camera/projector tests NOT RUN. Dual-webcam first-pattern timeout remains unresolved.", []string{"Guided Auto now creates and accepts its own fresh detected project before dot measurement, instead of silently adding to the old scene and stopping before calibration.", "Guided detection respects the Indoor/Outside setting from the first attempt. It no longer tries house detection first in an indoor room.", "The BIG VIEW outline photo and editing controls use separate columns, with object/type selection and Bigger/Smaller at the top.", "Click an outline in Live preview to select it; + and - resize it. Right-click keeps the existing type menu. Webcam-only preview stays pan/zoom because it is not registered to the saved outline photo.", "Dual-webcam timeout messages retain the last capture failure instead of discarding it; the hardware failure is not claimed fixed."}, []string{"Run Guided Auto once with the correct Indoor/Outside setting and send logs after it completes or stops. Do not treat the map as accurate until its measured check passes. No claim of physical alignment from software tests."}, ""},