feat(pbs): add sprite animation and shared Studio authoring
Implement DEC-0084 with factory-only Sprite/Animator structs, complete result lowering, validated animation sidecars, generated PBS factories and JavaFX/MCP authoring through shared services. Qualify native dev/release with ordinary and optimized producers, zero-allocation playback, private-cycle reclamation, canonical Composer pixels, installed JARs and JavaFX lifecycle. Preserve the runtime checkout and existing host ABI.
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
package p.studio.core.assets;
|
||||
|
||||
import p.studio.api.assets.animation.AnimationService;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Exported assets-module seam; the session module supplies existing authority and publication gates. */
|
||||
@FunctionalInterface
|
||||
public interface AnimationOperations {
|
||||
AnimationService.Response execute(AnimationService.Request request, Runnable authority, Consumer<Runnable> publication);
|
||||
}
|
||||
@@ -42,7 +42,7 @@ public final class PackerAssetCatalog implements AssetCatalog {
|
||||
AssetFamily.valueOf(summary.assetFamily().name()),
|
||||
summary.identity().assetRoot(),
|
||||
summary.preloadEnabled(),
|
||||
summary.hasDiagnostics()))
|
||||
summary.hasDiagnostics(), summary.identity().assetUuid()))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ public final class PackerAssetDetails implements AssetDetails {
|
||||
AssetFamily.valueOf(summary.assetFamily().name()),
|
||||
summary.identity().assetRoot(),
|
||||
summary.preloadEnabled(),
|
||||
summary.hasDiagnostics());
|
||||
summary.hasDiagnostics(), summary.identity().assetUuid());
|
||||
}
|
||||
|
||||
private static AssetConfigurationField field(PackerCodecConfigurationFieldDTO field) {
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package p.studio.core.assets.animation;
|
||||
|
||||
import p.animation.*;
|
||||
import p.studio.api.automation.CanonicalCapture;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
/** Toolkit-neutral rendering consumes the exact Packer material indices/palette bytes. */
|
||||
public final class AnimationPreviewRenderer {
|
||||
public CanonicalCapture render(GlyphBankLayout bank,AnimationTimeline.Observation frame,int paletteId,String revision) {
|
||||
byte[] palettes=bank.rgbaPalettes();
|
||||
if(paletteId<0||paletteId>=palettes.length/64)throw new IllegalArgumentException("invalid_palette");
|
||||
var glyph=bank.glyphs().stream().filter(g->g.glyphId()==frame.glyphId()&&g.artifactId().equals(frame.artifactId())).findFirst().orElseThrow(()->new IllegalArgumentException("unknown_glyph"));
|
||||
byte[] indices=glyph.indices();
|
||||
if(glyph.width()<=0||glyph.height()<=0||indices.length!=glyph.width()*glyph.height())throw new IllegalArgumentException("invalid_glyph_pixels");
|
||||
var image=new BufferedImage(glyph.width(),glyph.height(),BufferedImage.TYPE_INT_ARGB);
|
||||
for(int y=0;y<glyph.height();y++)for(int x=0;x<glyph.width();x++){
|
||||
int index=Byte.toUnsignedInt(indices[y*glyph.width()+x]);if(index>=16)throw new IllegalArgumentException("invalid_material_index");
|
||||
int offset=paletteId*64+index*4;
|
||||
int rgba=(Byte.toUnsignedInt(palettes[offset])<<24)|(Byte.toUnsignedInt(palettes[offset+1])<<16)|(Byte.toUnsignedInt(palettes[offset+2])<<8)|Byte.toUnsignedInt(palettes[offset+3]);
|
||||
image.setRGB(x,y,(rgba>>>8)|((rgba&255)<<24));
|
||||
}
|
||||
try(var out=new ByteArrayOutputStream()){
|
||||
if(!ImageIO.write(image,"png",out))throw new IllegalStateException("PNG encoder unavailable");
|
||||
return new CanonicalCapture("animation:"+bank.assetUuid(),revision,frame.phase(),frame.phase(),glyph.width(),glyph.height(),glyph.width(),out.toByteArray());
|
||||
}catch(java.io.IOException error){throw new IllegalStateException("Preview encoding failed",error);}
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package p.studio.core.assets.animation;
|
||||
|
||||
import p.animation.*;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.animation.AnimationService;
|
||||
import java.nio.file.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Shared application service. Manual/task adapters supply existing authority before entry. */
|
||||
public final class DefaultAnimationService implements p.studio.core.assets.AnimationOperations {
|
||||
private final GlyphBankLayoutSource layouts;private final AssetCatalog assets;
|
||||
private final AnimationCodec codec=new AnimationCodec();private final AnimationValidator validator=new AnimationValidator();
|
||||
private final AnimationPreviewRenderer renderer=new AnimationPreviewRenderer();
|
||||
public DefaultAnimationService(GlyphBankLayoutSource layouts,AssetCatalog assets){this.layouts=Objects.requireNonNull(layouts);this.assets=Objects.requireNonNull(assets);}
|
||||
public AnimationService.Response execute(AnimationService.Request request,Runnable authority,Consumer<Runnable> publication) {
|
||||
authority.run();checkCancellation();
|
||||
if(request.operation()==AnimationService.Operation.LIST){
|
||||
var views=new ArrayList<AnimationService.View>();
|
||||
for(var asset:assets.list(request.project(),false)){
|
||||
if(asset.family()!=AssetFamily.GLYPH_BANK||asset.registrationState()!=AssetRegistrationState.REGISTERED)continue;
|
||||
try {
|
||||
var node=new com.fasterxml.jackson.databind.ObjectMapper().readTree(asset.root().resolve("asset.json").toFile());
|
||||
var uuid=UUID.fromString(node.path("asset_uuid").asText());
|
||||
if(request.assetUuid()==null||request.assetUuid().equals(uuid))views.add(execute(AnimationService.Request.get(request.project(),uuid),authority,publication).view());
|
||||
} catch(java.io.IOException|IllegalArgumentException failure){
|
||||
// Report malformed registered definitions rather than returning a stale cached catalog.
|
||||
views.add(new AnimationService.View(null,null,"",null,List.of(),"",List.of(new AnimationDiagnostic("bank_read","",failure.getMessage()))));
|
||||
}
|
||||
}
|
||||
authority.run();return new AnimationService.Response(null,views,null,null,views.stream().flatMap(v->v.diagnostics().stream()).toList());
|
||||
}
|
||||
Objects.requireNonNull(request.assetUuid(),"assetUuid");
|
||||
return layouts.withLayout(request.project().rootPath(),request.assetUuid(),bank->{
|
||||
authority.run();checkCancellation();Path file=definitionPath(request,bank);
|
||||
var current=read(file,bank);var candidate=request.document()==null?current.document():request.document();
|
||||
return switch(request.operation()) {
|
||||
case GET -> AnimationService.Response.of(current);
|
||||
case VALIDATE -> candidate==null?AnimationService.Response.of(current):AnimationService.Response.of(view(bank,current.revision(),codec.encode(candidate),candidate));
|
||||
case PREVIEW -> {
|
||||
if(candidate==null)throw new IllegalArgumentException("No valid animation document");validator.requireValid(candidate,bank);
|
||||
if(request.elapsedTicks()==null||request.paletteId()==null)throw new IllegalArgumentException("elapsedTicks and paletteId are required");
|
||||
var observation=AnimationTimeline.sample(candidate,Objects.requireNonNull(request.animatorId()),Objects.requireNonNull(request.clipName()),request.elapsedTicks());
|
||||
String revision=request.document()==null?current.revision():AnimationRevision.of(codec.encode(candidate));
|
||||
var preview=new AnimationService.Preview(bank.assetUuid(),revision,observation,request.elapsedTicks(),request.paletteId(),renderer.render(bank,observation,request.paletteId(),revision));
|
||||
authority.run();yield new AnimationService.Response(current,List.of(),preview,null,List.of());
|
||||
}
|
||||
case SAVE -> {
|
||||
Objects.requireNonNull(request.document(),"document");validator.requireValid(request.document(),bank);
|
||||
write(file,request.expectedRevision(),request.document(),publication);yield AnimationService.Response.of(read(file,bank));
|
||||
}
|
||||
case DELETE -> {
|
||||
requireRevision(request.expectedRevision(),current.revision());
|
||||
if(current.document()==null)throw new IllegalArgumentException("Repair the malformed document before deleting a definition");
|
||||
var remaining=current.document().animators().stream().filter(a->!a.id().equals(request.animatorId())).toList();
|
||||
if(remaining.size()==current.document().animators().size())throw new IllegalArgumentException("unknown_animator");
|
||||
var next=new AnimationDocument(1,current.document().bankAssetUuid(),current.document().bindings(),remaining);validator.requireValid(next,bank);
|
||||
write(file,request.expectedRevision(),next,publication);yield AnimationService.Response.of(read(file,bank));
|
||||
}
|
||||
case PREPARE_REBIND -> {
|
||||
requireRevision(request.expectedRevision(),current.revision());
|
||||
if(current.document()==null)throw new IllegalArgumentException("Repair malformed JSON before rebind");
|
||||
var proposal=new AnimationRebind().prepare(current.document(),current.revision(),bank);
|
||||
yield new AnimationService.Response(current,List.of(),null,proposal,validator.validate(proposal.document(),bank));
|
||||
}
|
||||
case APPLY_REBIND -> {
|
||||
requireRevision(request.expectedRevision(),current.revision());
|
||||
if(current.document()==null)throw new IllegalArgumentException("Repair malformed JSON before rebind");
|
||||
var proposal=new AnimationRebind().prepare(current.document(),current.revision(),bank);
|
||||
if(!Objects.equals(bank.revision(),request.expectedBankRevision())||!Objects.equals(proposal.proposalHash(),request.proposalHash())||!Objects.equals(proposal.document(),request.document()))
|
||||
throw new IllegalStateException("Animation rebind conflict: proposal or bank revision changed");
|
||||
validator.requireValid(proposal.document(),bank);write(file,request.expectedRevision(),proposal.document(),publication);
|
||||
yield AnimationService.Response.of(read(file,bank));
|
||||
}
|
||||
case LIST -> throw new AssertionError();
|
||||
};
|
||||
});
|
||||
}
|
||||
private Path definitionPath(AnimationService.Request request,GlyphBankLayout bank){
|
||||
try {
|
||||
Path assets=request.project().rootPath().resolve("assets").toRealPath();Path root=bank.assetRoot().toRealPath();
|
||||
if(!root.startsWith(assets)||!bank.assetUuid().equals(request.assetUuid()))throw new IllegalArgumentException("Bank lies outside project asset scope");
|
||||
Path file=root.resolve(AnimationDocument.FILE_NAME);if(Files.isSymbolicLink(file))throw new IllegalArgumentException("Animation sidecar must not be a symbolic link");return file;
|
||||
}catch(java.io.IOException failure){throw new IllegalStateException("Cannot resolve registered bank",failure);}
|
||||
}
|
||||
private AnimationService.View read(Path file,GlyphBankLayout bank){
|
||||
try {
|
||||
if(!Files.exists(file))return view(bank,null,"",null);
|
||||
String text=Files.readString(file,StandardCharsets.UTF_8);String revision=AnimationRevision.of(text);
|
||||
try{return view(bank,revision,text,codec.decode(text));}
|
||||
catch(IllegalArgumentException error){return new AnimationService.View(bank.assetUuid(),revision,text,null,available(bank),bank.revision(),List.of(new AnimationDiagnostic("invalid_json","",error.getMessage())));}
|
||||
}catch(java.io.IOException failure){throw new IllegalStateException("Cannot read animation definition",failure);}
|
||||
}
|
||||
private AnimationService.View view(GlyphBankLayout bank,String revision,String json,AnimationDocument doc){return new AnimationService.View(bank.assetUuid(),revision,json,doc,available(bank),bank.revision(),doc==null?List.of():validator.validate(doc,bank));}
|
||||
private static List<AnimationDocument.Binding> available(GlyphBankLayout bank){return bank.glyphs().stream().map(g->new AnimationDocument.Binding(g.artifactId(),g.glyphId(),g.fingerprint())).toList();}
|
||||
private void write(Path file,String expected,AnimationDocument candidate,Consumer<Runnable> publication){
|
||||
byte[] encoded=codec.encode(candidate).getBytes(StandardCharsets.UTF_8);
|
||||
publication.accept(()->{
|
||||
checkCancellation();
|
||||
try {
|
||||
String actual=Files.exists(file)?AnimationRevision.of(Files.readAllBytes(file)):null;requireRevision(expected,actual);
|
||||
Path temporary=Files.createTempFile(file.getParent(),".animation-",".tmp");
|
||||
try{Files.write(temporary,encoded);checkCancellation();Files.move(temporary,file,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);}
|
||||
finally{Files.deleteIfExists(temporary);}
|
||||
}catch(java.io.IOException failure){throw new IllegalStateException("Atomic animation save failed",failure);}
|
||||
});
|
||||
}
|
||||
private static void requireRevision(String expected,String actual){if(!Objects.equals(expected,actual))throw new IllegalStateException("Animation revision conflict");}
|
||||
private static void checkCancellation(){if(Thread.currentThread().isInterrupted())throw new java.util.concurrent.CancellationException("Animation operation cancelled");}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package p.studio.core.assets.animation;
|
||||
import p.studio.api.assets.animation.AnimationService;
|
||||
import p.studio.api.automation.ProjectAccess;
|
||||
import java.util.concurrent.CancellationException;
|
||||
/** UI adapter holds the existing manual lease for the full operation. */
|
||||
public final class ManualAnimationService implements AnimationService {
|
||||
private final DefaultAnimationService service;private final ProjectAccess access;
|
||||
public ManualAnimationService(DefaultAnimationService service,ProjectAccess access){this.service=service;this.access=access;}
|
||||
@Override public Response execute(Request request){
|
||||
try(var lease=access.enterManual(request.project().rootPath())){
|
||||
Object lock=new Object();boolean[] cancelled={false};
|
||||
lease.onProjectClose(()->{synchronized(lock){cancelled[0]=true;}});
|
||||
Runnable check=()->{synchronized(lock){if(cancelled[0])throw new CancellationException("Project closed");}};
|
||||
return service.execute(request,check,work->{synchronized(lock){check.run();work.run();}});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package p.studio.core.session;
|
||||
import p.studio.api.assets.animation.*;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.core.assets.AnimationOperations;
|
||||
import p.studio.core.project.ProjectAccessRegistry;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Function;
|
||||
|
||||
/** Existing task lifecycle owns admission, cancellation and atomic publication. */
|
||||
public final class TaskAnimationService implements AnimationTasks {
|
||||
private final ProjectAccessRegistry projects;private final ProjectCatalog catalog;private final AnimationOperations service;
|
||||
public TaskAnimationService(ProjectAccessRegistry projects,ProjectCatalog catalog,AnimationOperations service){this.projects=projects;this.catalog=catalog;this.service=service;}
|
||||
@Override public AnimationService.Response execute(Path root,String id,Function<ProjectReference,AnimationService.Request> factory){
|
||||
var session=projects.requireAutomation(root);var task=requireTask(session,id);
|
||||
var result=new AtomicReference<AnimationService.Response>();
|
||||
var cancelled=new java.util.concurrent.atomic.AtomicBoolean();
|
||||
var handle=session.submit(task,"Animation authoring",()->{
|
||||
requireTask(session,id);var request=factory.apply(catalog.openProject(root));
|
||||
if(!request.project().rootPath().equals(task.projectRoot()))throw new AutomationException(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE,"Animation request changed project scope");
|
||||
Thread owner=Thread.currentThread();
|
||||
Runnable admitted=()->{requireTask(session,id);if(cancelled.get()||owner.isInterrupted())throw new CancellationException();};
|
||||
try { result.set(service.execute(request,admitted,work->{synchronized(session){admitted.run();work.run();}})); }
|
||||
finally { if(owner.isInterrupted())cancelled.set(true); }
|
||||
return new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED,0,0,List.of(),null);
|
||||
});
|
||||
var cancellation=handle.subscribe(snapshot->{if(snapshot.state()==p.studio.api.operation.OperationState.CANCELLED)cancelled.set(true);});
|
||||
try {
|
||||
handle.completion().handle((value,error)->null).thenCompose(ignored->handle.termination()).toCompletableFuture().get(12,TimeUnit.SECONDS);
|
||||
handle.completion().toCompletableFuture().get();requireTask(session,id);return Objects.requireNonNull(result.get());
|
||||
}catch(ExecutionException error){if(error.getCause() instanceof RuntimeException cause)throw cause;throw new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE,"Animation operation failed");}
|
||||
catch(InterruptedException error){handle.cancel();Thread.currentThread().interrupt();throw new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE,"Animation operation interrupted");}
|
||||
catch(TimeoutException|CancellationException error){cancelled.set(true);handle.cancel();throw new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE,"Animation operation cancelled or timed out");}
|
||||
finally { cancellation.unsubscribe(); }
|
||||
}
|
||||
private static TaskIdentity requireTask(AutomationSession session,String id){var snapshot=session.snapshot();
|
||||
if(snapshot.closed()||snapshot.state()!=ControlState.AGENT_WORKING||snapshot.task()==null||!snapshot.task().value().equals(id))throw new ControlDeniedException(ControlResult.Status.INVALID_TASK);
|
||||
return snapshot.task();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user