diff --git a/README.md b/README.md index a48ebaf..a85cc8d 100644 --- a/README.md +++ b/README.md @@ -3,76 +3,84 @@ Terrain-aware procedural castles and independent culture regions for Minecraft. Original idea: Emre's brother. Concept and project direction: Emre (`badmon61`). -## Status: 0.1.0-alpha.1 — manual prototype +## Status: 0.2.0-alpha.1 — opt-in terraced architecture -**Use disposable test worlds only. This is not the finished world-generation mod.** -The first milestone provides real generator code and a Fabric adapter, not the final visual quality, mountain planning, population system or giant fantasy monuments. +**Disposable test worlds only. No automatic world generation and no completed in-game acceptance test.** -### Implemented +The original small castle remains available. A new, separate planner adds an asymmetric reference complex with three individually elevated courtyards, eight building modules, terrain-oriented placement, stairs and short supported bridges. This is an engineering alpha, not the final visual quality or an unrestricted mountain/monument generator. -- Deterministic, jittered Voronoi culture regions with eight stable culture IDs. -- Default culture scale: **7 × a configured linear biome reference**. The fallback reference is 1,024 blocks, giving 7,168-block nominal site spacing. These are design defaults, **not measured vanilla biome dimensions**, fixed region diameters or seven-biome counts. -- Generation version and scale captured per save; subsequent changes to global defaults do not rescale an existing save. -- One procedural prototype castle family with dimension/height variations, four towers, curtain walls, wall walks, a raised keep, interior floors, windows, ladders and an entrance ramp. -- Restored, weathered and ruined states; cultural vanilla-block palettes and a basic sandy-ground adaptation. Eight palettes do **not** yet mean eight different architectural grammars. -- Dry, already-loaded terrain sampling; limited foundations on gentle slopes; unsuitable sites rejected rather than carved through mountains. -- Operator-only textual preview, explicit placement confirmation, bounded build work, cancel and conflict-aware in-memory undo. -- Independent Java core verification across 50 castle seeds. +### New in this branch -### Not implemented yet +- Three offset, chamfered enclosures: outer bailey, residential court and upper keep; foundations are calculated per terrace rather than flattening the entire site to one height. +- Eight modules: service hall, outer tower, great hall, gallery/workshop, keep, two upper towers and gatehouse. Layout dimensions, offsets, heights, orientation, roofs and condition vary deterministically. +- Four roof forms: gable, hip, spire and battlement. Some choices depend on culture; these are **not eight complete independent architectural grammars**. +- Ground-aware stair connections and short beam/pier bridge sections. Unsuitable slopes, obstacles and excessive support depths are rejected before any block placement. +- Room/storey targets, four wall-walk targets per courtyard and a protected entrance corridor. A conservative navigation check rejects inaccessible plans. +- Ordered structural placement before rotated ladders. Preview confirmation now rechecks unchanged air/doorway cells and sampled ground as well as the write set. Undo tolerates automatic stair-shape updates, but not changed stair material, facing, half or waterlogging. +- Module construction-phase metadata and coherent weathering patches. This is the foundation for construction history, **not a simulation of centuries or structural collapse**. -Automatic generation during exploration; automatic biome-scale detection; full terrain terraces and bridges; huge castles and monuments; inhabitants and loot; cultural architecture blending; roads and settlements; Bedrock, consoles and NeoForge. No modpack compatibility or FPS guarantees. +### Retained -## First test +Deterministic culture geography, eight stable culture IDs, and **7 × the configured linear biome reference**. The default reference is 1,024 blocks, resulting in 7,168-block nominal region-site spacing. It is not a measured vanilla biome size or a fixed region diameter. Per-save generation settings and the classic planner are unchanged. -Runtime target: **Minecraft Java 26.1.2**, **Java 25**, **Fabric Loader 0.19.5+**, **Fabric API 0.155.3+26.1.2**. +### Still outside this milestone -1. Create a separate Prism/Fabric test instance. Do not install this first alpha into a valuable survival world. -2. Get the `castleforge-fabric-26.1.2` artifact from a successful GitHub Actions run. Install `castleforge-fabric-0.1.0-alpha.1.jar` and Fabric API; **do not install the `-sources.jar`**. -3. Create a new Creative superflat world with commands enabled. Remain near the site while building or undoing. -4. Run these separately: +Automatic exploration-time generation; automatically measured biome scaling; arbitrary contour-following castle grammars; giant monuments; inhabitants, loot and furnishing; roads/settlements; Bedrock, consoles and NeoForge. No general modpack compatibility, FPS or runtime-physics guarantee. + +## Test installation + +Target remains **Minecraft Java 26.1.2**, **Java 25**, **Fabric Loader 0.19.5+**, **Fabric API 0.155.3+26.1.2**. + +1. Use a separate Prism/Fabric instance and a new disposable Creative world with commands enabled. +2. Install `castleforge-fabric-0.2.0-alpha.1.jar` from a successful branch Actions build plus the matching Fabric API. Replace the old CastleForge JAR; do not install two versions or a `-sources.jar`. +3. Start on superflat to verify the build workflow, then test a second disposable world with open, gradual slopes. The new survey is 105 × 105 blocks; the whole site must already be loaded. +4. Execute separately: ```mcfunction /castleforge region -/castleforge preview +/castleforge preview terraced /castleforge build confirm /castleforge status ``` -Without coordinates, preview selects a site 28 blocks north of you. It only prints a report; it is not a ghost-block visual preview. Confirmation expires after 120 seconds. Explicit coordinates are supported with `/castleforge preview `. +The default new site is centred 56 blocks north of you. Its entrance may face another direction because the planner rotates to fit terrain. Explicit coordinates work with `/castleforge preview terraced `. Preview is a **text report**, not a visual ghost building. Confirmation expires after 120 seconds. Stay near the entire build area. + +The original generator is still selected by `/castleforge preview` or `/castleforge preview `; its default centre remains 28 blocks north of you. ```mcfunction /castleforge cancel /castleforge undo ``` -Cancel stops future edits; **it does not immediately remove the partial building**. Undo operates on the last build by that operator, in the current server session, skipping blocks subsequently changed by someone else. Starting another build replaces the old undo history. Closing the world, stopping or crashing the server loses undo. Physics side effects are not comprehensively journaled. **Undo is not a backup.** +Cancel leaves a partial building. Undo only covers the last build in this server session and is lost on server shutdown, world close, crash or the next build. It skips conflicting later edits, with the documented exception for automatically recomputed stair shape. It does not journal every neighboring physics effect. **Undo is not a backup.** -All commands require Minecraft moderator permission / enabled cheats. No chunks are force-loaded. There is no automatic placement on world load. +All commands require moderator permission/cheats. No chunks are force-loaded. Terrain sampling and planning are bounded but synchronous: a preview can still briefly stall a tick. Placement uses the existing cooperative per-tick budget; a single Minecraft block update can exceed it. -## Configuration +## Generation settings -Optionally copy `config/castleforge.example.properties` to the instance's `config/castleforge.properties` **before first use in a new save**. The chosen generation values are stored in `/castleforge/generation-v1.properties`. Do not edit or delete that file on a world you intend to preserve. Unknown algorithm versions fail closed. +Optionally copy `config/castleforge.example.properties` to the instance's `config/castleforge.properties` before first use in a new save. Settings are captured in `/castleforge/generation-v1.properties`. Do not alter/delete this file on a world you intend to preserve. This architecture change does not rescale or reshuffle culture regions. -## Build +## Build and verification -Install JDK 25 and Gradle **9.4.0**, then: +Use JDK 25 and Gradle 9.4.0: ```sh gradle --no-daemon build gradle :fabric:runClient ``` -A Gradle wrapper is not yet checked in; the CI explicitly installs the pinned Gradle release. The core itself targets Java 21 and has no Minecraft dependency. Its offline verification can run with JDK 21+: +The CI uses pinned Gradle; a Gradle wrapper is not yet checked in. Pure generator tests also run with JDK 21+: ```sh bash scripts/verify-core.sh ``` -See [architecture](docs/ARCHITECTURE.md), [test checklist](docs/TESTING.md), [validation record](docs/VALIDATION.md), and [roadmap](docs/ROADMAP.md). +The classic suite checks 50 seeds. The new suite checks **32 seeds × 5 synthetic terrains = 160 combinations**, all eight culture profiles, all four rotations, roofs and condition states, determinism, navigation, bounded supports, rejection cases, negative/world-edge coordinates and concurrent planning. A golden geometry digest detects unintended generator drift. Repeated per-voxel assertions are not millions of different test scenarios. + +Passing these checks is **not a Minecraft launch, entity-pathfinding, block-physics or visual test**. See [terraced architecture and acceptance checklist](docs/TERRACED_ARCHITECTURE.md), [original architecture](docs/ARCHITECTURE.md), [classic test checklist](docs/TESTING.md), [initial alpha validation](docs/VALIDATION.md), and [long-term roadmap](docs/ROADMAP.md). ## Licensing -A redistribution license has not been selected. Do not assume that public visibility grants open-source redistribution rights. No Mojang binaries, third-party schematics or texture assets are included. +A redistribution license has not been selected. Public visibility does not grant a redistribution license. No Mojang binaries, third-party schematics or texture assets are included. Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft. diff --git a/build.gradle b/build.gradle index 0b8021f..a96dda7 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ plugins { } allprojects { group = 'dev.castleforge' - version = '0.1.0-alpha.1' + version = '0.2.0-alpha.1' repositories { mavenCentral() } } tasks.named('build') { dependsOn ':core:build', ':fabric:build' } diff --git a/core/build.gradle b/core/build.gradle index 47de4f9..9689425 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -1,7 +1,7 @@ plugins { id 'java-library' } java { toolchain { languageVersion = JavaLanguageVersion.of(25) } } tasks.withType(JavaCompile).configureEach { options.release = 21 } -// Tests deliberately use no external framework: also runnable offline with javac/java 21. +// Dependency-free suites also run offline with javac/java 21. tasks.named('test') { enabled = false } tasks.register('verifyCore', JavaExec) { dependsOn testClasses @@ -9,4 +9,11 @@ tasks.register('verifyCore', JavaExec) { mainClass = 'dev.castleforge.core.CoreVerification' maxHeapSize = '512m' } -tasks.named('check') { dependsOn verifyCore } +tasks.register('verifyTerraces', JavaExec) { + dependsOn testClasses + classpath = sourceSets.test.runtimeClasspath + mainClass = 'dev.castleforge.core.TerracedVerification' + maxHeapSize = '512m' + mustRunAfter verifyCore +} +tasks.named('check') { dependsOn verifyCore, verifyTerraces } diff --git a/core/src/main/java/dev/castleforge/core/PlanNavigation.java b/core/src/main/java/dev/castleforge/core/PlanNavigation.java new file mode 100644 index 0000000..5d026c4 --- /dev/null +++ b/core/src/main/java/dev/castleforge/core/PlanNavigation.java @@ -0,0 +1,71 @@ +package dev.castleforge.core; + +import java.util.*; +import static dev.castleforge.core.CastlePlanner.Pos; +import static dev.castleforge.core.TerracedCastlePlanner.*; + +/** Conservative full-cube walking model, NOT Minecraft physics/entity pathfinding. */ +public final class PlanNavigation { + private static final int MAX_VISITED=100_000; + public record Result(int reached,int targets) {} + public static Result verify(Plan plan,Ground ground) { + Map blocks=new HashMap<>(); + for(Block block:plan.blocks()) { + if(blocks.put(block.pos(),block)!=null) throw new IllegalArgumentException("Duplicate planned position"); + if(block.pos().y() remaining=new HashSet<>(); + for(Target target:plan.targets()) { + if(!space.stand(target.feet())) throw new IllegalArgumentException("Blocked room target: "+target.id()+" at "+target.feet()); + remaining.add(target.feet()); + } + ArrayDeque todo=new ArrayDeque<>(); Set seen=new HashSet<>(); + todo.add(plan.entrance()); seen.add(plan.entrance()); remaining.remove(plan.entrance()); + while(!todo.isEmpty() && !remaining.isEmpty()) { + Pos p=todo.removeFirst(); + for(Facing d:Facing.values()) for(int dy=-1;dy<=1;dy++) { + Pos next=new Pos(p.x()+d.dx,p.y()+dy,p.z()+d.dz); + if(dy>0 && !space.clear(new Pos(p.x(),p.y()+2,p.z()))) continue; + if(dy<0 && !space.clear(new Pos(next.x(),next.y()+2,next.z()))) continue; + visit(space,next,todo,seen,remaining); + } + if(space.ladder(p) || space.ladder(new Pos(p.x(),p.y()-1,p.z()))) + for(int dy:new int[]{-1,1}) visit(space,new Pos(p.x(),p.y()+dy,p.z()),todo,seen,remaining); + if(seen.size()>MAX_VISITED) throw new IllegalArgumentException("Navigation budget exceeded"); + } + if(!remaining.isEmpty()) { + String names=plan.targets().stream().filter(t->remaining.contains(t.feet())).map(Target::id).toList().toString(); + throw new IllegalArgumentException("Unreachable architecture targets: "+names); + } + return new Result(seen.size(),plan.targets().size()); + } + private static void visit(Space s,Pos p,ArrayDeque todo,Set seen,Set remaining) { + if(s.inBounds(p) && !seen.contains(p) && s.stand(p)) { seen.add(p); todo.add(p); remaining.remove(p); } + } + private record Space(Plan plan,Ground ground,Map blocks) { + boolean inBounds(Pos p) { + return Math.abs((long)p.x()-plan.originX())<=RADIUS && Math.abs((long)p.z()-plan.originZ())<=RADIUS + && p.y()>=-1024 && p.y()<=4200; + } + Kind kind(Pos p) { + Block block=blocks.get(p); if(block!=null) return block.kind(); + int h=ground.surfaceY(p.x(),p.z()); + return h==UNUSABLE || p.y() feet) { + public Link { feet=List.copyOf(feet); } + } + public record Plan(List blocks, List terraces, List rooms, List links, + List targets, Pos entrance, int quarterTurns, Condition condition, + CultureMap.Region region, int originX, int originZ) { + public Plan { + blocks=List.copyOf(blocks); terraces=List.copyOf(terraces); rooms=List.copyOf(rooms); + links=List.copyOf(links); targets=List.copyOf(targets); + } + public int relief() { return terraces.stream().mapToInt(Terrace::floorY).max().orElseThrow() + - terraces.stream().mapToInt(Terrace::floorY).min().orElseThrow(); } + } + @FunctionalInterface public interface Ground { int surfaceY(int x,int z); } + + public static Plan plan(long seed,int ox,int oz,Ground ground,CultureMap.Region region) { + Objects.requireNonNull(ground); Objects.requireNonNull(region); + if (Math.abs((long)ox)>29_999_800 || Math.abs((long)oz)>29_999_800) + throw new IllegalArgumentException("Site too near world coordinate limit"); + Survey survey=new Survey(ox,oz,ground); + long site=CultureMap.hash(seed ^ 0x5445525241434531L,ox,oz); + Condition condition=Condition.values()[Math.floorMod(CultureMap.mix(site),3)]; + List candidates=new ArrayList<>(); + for (int q=0;q<4;q++) { + try { candidates.add(candidate(site,survey,q)); } + catch (IllegalArgumentException ignored) { /* Try other orientations without writes. */ } + } + candidates.sort(Comparator.comparingLong(Candidate::score).thenComparingInt(Candidate::turns)); + String reason="No orientation fits dry terrain within the foundation limit"; + for (Candidate candidate : candidates) { + try { + Builder b=new Builder(site,survey,candidate.turns,condition,region,ox,oz); + Plan result=b.build(candidate.terraces); + PlanNavigation.verify(result,survey::worldHeight); + return result; + } catch (IllegalArgumentException e) { reason=e.getMessage(); } + } + throw new IllegalArgumentException("Terraced site rejected: " + reason); + } + private record Candidate(int turns,List terraces,long score) {} + private static Candidate candidate(long seed,Survey s,int q) { + List terraces=new ArrayList<>(); long score=0; + int[] centers={28,0,-28}; String[] names={"outer_bailey","residential_court","upper_keep"}; + int[] offsets={-4,5,-2}; + for (int i=0;i<3;i++) { + Rect r=new Rect(offsets[i]+random(seed,100+i,5)-2,centers[i],21+random(seed,200+i,3),11+random(seed,300+i,2)); + int min=Integer.MAX_VALUE,max=Integer.MIN_VALUE; + for (int x=r.x-r.rx;x<=r.x+r.rx;x++) for (int z=r.z-r.rz;z<=r.z+r.rz;z++) if (r.contains(x,z)) { + int h=s.local(q,x,z); if (h==UNUSABLE) throw new IllegalArgumentException("Unsuitable terrace ground"); + min=Math.min(min,h); max=Math.max(max,h); + } + if (max-min>MAX_FOUNDATION) throw new IllegalArgumentException("Local relief exceeds eight-block foundation limit"); + terraces.add(new Terrace(names[i],r,max,max-min)); + for (int x=r.x-r.rx;x<=r.x+r.rx;x++) for (int z=r.z-r.rz;z<=r.z+r.rz;z++) + if (r.contains(x,z)) score+=max-s.local(q,x,z); + } + // Prefer a keep uphill of the entrance, without forcing a fixed compass direction. + int rise=terraces.get(2).floorY-terraces.get(0).floorY; + if (Math.abs(rise)>24) throw new IllegalArgumentException("Site relief exceeds the reference design budget"); + score+=Math.max(0,-rise)*10_000L; + score+=random(seed,400+q,31); + return new Candidate(q,List.copyOf(terraces),score); + } + private static int random(long seed,int salt,int bound) { return Math.floorMod(CultureMap.mix(seed ^ salt),bound); } + private static Cell rotate(int q,int x,int z) { + return switch(q) { case 0 -> new Cell(x,z); case 1 -> new Cell(-z,x); + case 2 -> new Cell(-x,-z); case 3 -> new Cell(z,-x); default -> throw new IllegalArgumentException("Rotation"); }; + } + private static final class Survey { + final int ox,oz; final int[][] heights=new int[2*RADIUS+1][2*RADIUS+1]; + Survey(int ox,int oz,Ground ground) { + this.ox=ox; this.oz=oz; + for(int x=-RADIUS;x<=RADIUS;x++) for(int z=-RADIUS;z<=RADIUS;z++) { + int h=ground.surfaceY(ox+x,oz+z); + if(h!=UNUSABLE && (h< -1024 || h>4096)) throw new IllegalArgumentException("Unsupported terrain height"); + heights[x+RADIUS][z+RADIUS]=h; + } + } + int worldHeight(int x,int z) { + int dx=x-ox,dz=z-oz; + if(Math.abs(dx)>RADIUS || Math.abs(dz)>RADIUS) return UNUSABLE; + return heights[dx+RADIUS][dz+RADIUS]; + } + int local(int q,int x,int z) { Cell p=rotate(q,x,z); return worldHeight(ox+p.x,oz+p.z); } + } + private static final class Builder { + final long seed; final Survey survey; final int q,ox,oz; final Condition condition; final CultureMap.Region region; + final Map blocks=new HashMap<>(); + final List rooms=new ArrayList<>(); final List targets=new ArrayList<>(); final List links=new ArrayList<>(); + Builder(long seed,Survey survey,int q,Condition condition,CultureMap.Region region,int ox,int oz) { + this.seed=seed; this.survey=survey; this.q=q; this.condition=condition; this.region=region; this.ox=ox; this.oz=oz; + } + int ground(int x,int z) { + int h=survey.local(q,x,z); + if(h==UNUSABLE) throw new IllegalArgumentException("A used footprint contains unsuitable terrain"); + return h; + } + Pos world(int x,int y,int z) { Cell p=rotate(q,x,z); return new Pos(ox+p.x,y,oz+p.z); } + void put(int x,int y,int z,Kind kind) { put(x,y,z,kind,Facing.NORTH); } + void put(int x,int y,int z,Kind kind,Facing facing) { + if(Math.abs(x)>RADIUS || Math.abs(z)>RADIUS) throw new IllegalArgumentException("Geometry exceeds survey"); + if(yMAX_BLOCKS) throw new IllegalArgumentException("Architecture block budget exceeded"); + } + void stone(int x,int y,int z,int phase) { + int weather=condition==Condition.RESTORED?8:condition==Condition.WEATHERED?36:65; + weather=Math.max(0,weather-phase*9); + long patch=CultureMap.hash(seed ^ Math.floorDiv(y,3),Math.floorDiv(x,4),Math.floorDiv(z,4)); + put(x,y,z,Math.floorMod(patch,100) ts) { + for(Terrace t:ts) terrace(t); + Terrace lower=ts.get(0),middle=ts.get(1),upper=ts.get(2); + Rect a=lower.footprint,b=middle.footprint,c=upper.footprint; + room(new Room("service_hall","stores_and_kitchen",new Rect(a.x-11,a.z,5,4),lower.floorY,1,roof(false),1),false); + room(new Room("outer_tower","watchtower",new Rect(a.x+11,a.z,4,4),lower.floorY,2,roof(true),1),true); + room(new Room("great_hall","residence",new Rect(b.x-11,b.z,6,5),middle.floorY,2,roof(false),1),false); + room(new Room("gallery","workshop",new Rect(b.x+11,b.z,4,5),middle.floorY,1,Roof.HIP,2),false); + room(new Room("keep","oldest_core",new Rect(c.x,c.z-1,6,6),upper.floorY,3,roof(false),0),false); + room(new Room("west_tower","watchtower",new Rect(c.x-14,c.z,3,3),upper.floorY,2,roof(true),0),true); + room(new Room("east_tower","watchtower",new Rect(c.x+14,c.z,3,3),upper.floorY,2+random(seed,17,2),roof(true),0),true); + gatehouse(lower); + connect("lower_to_residence",lower,middle); + connect("residence_to_keep",middle,upper); + List approach=line(new Cell(a.x,a.z+a.rz),new Cell(a.x,RADIUS-1)); + int end=ground(a.x,RADIUS-1)-1; + path("entrance_approach",approach,lower.floorY,end); + Pos entrance=world(a.x,ground(a.x,RADIUS),RADIUS); + target("outside_entrance",a.x,ground(a.x,RADIUS),RADIUS); + List ordered=blocks.values().stream().sorted(Comparator + .comparingInt((Block v)->v.kind==Kind.LADDER?1:0) + .thenComparingInt(v->v.pos.y()).thenComparingInt(v->v.pos.z()).thenComparingInt(v->v.pos.x())).toList(); + return new Plan(ordered,ts,rooms,links,targets,entrance,q,condition,region,ox,oz); + } + Roof roof(boolean tower) { + if(region.style().equals("desert_citadel") || region.style().equals("mediterranean")) return Roof.BATTLEMENT; + if(tower) return region.style().equals("maritime")?Roof.BATTLEMENT:Roof.SPIRE; + return region.style().equals("high_fantasy")?Roof.HIP:Roof.GABLE; + } + void terrace(Terrace t) { + Rect r=t.footprint; int f=t.floorY; + for(int x=r.x-r.rx;x<=r.x+r.rx;x++) for(int z=r.z-r.rz;z<=r.z+r.rz;z++) if(r.contains(x,z)) { + for(int y=ground(x,z);ytg.id.startsWith("gatehouse/")); + target("gatehouse/chamber",cx+1,f+6,cz); + target("gatehouse/roof",cx+1,f+12,cz); + } + void connect(String id,Terrace from,Terrace to) { + Cell start=new Cell(from.footprint.x,from.footprint.z-from.footprint.rz); + Cell end=new Cell(to.footprint.x,to.footprint.z+to.footprint.rz); + int middleZ=Math.floorDiv(start.z+end.z,2); + List path=new ArrayList<>(); + append(path,line(start,new Cell(start.x,middleZ))); + append(path,line(new Cell(start.x,middleZ),new Cell(end.x,middleZ))); + append(path,line(new Cell(end.x,middleZ),end)); + path(id,path,from.floorY,to.floorY); + } + void path(String id,List route,int start,int end) { + int n=route.size(); int[] levels=new int[n]; + for(int i=0;i=0;i--) levels[i]=Math.max(levels[i],levels[i+1]-1); + if(levels[0]>start || levels[n-1]>end) throw new IllegalArgumentException("A connecting stair cannot meet both terrace gates"); + Map deck=new LinkedHashMap<>(); + Map station=new HashMap<>(); + for(int i=0;ie.getValue()-ground(e.getKey().x,e.getKey().z)>=4); + Set centerline=new HashSet<>(route); + for(var e:deck.entrySet()) { + Cell p=e.getKey(); int y=e.getValue(),h=ground(p.x,p.z),at=station.get(p); + if(y-h>MAX_PIER) throw new IllegalArgumentException("Bridge or stair requires overlong supports"); + if(y=h) { + boolean pier=!bridge || at%5==0 || at<=1 || at>=n-2; + if(pier) for(int fy=h;fy=h) put(p.x,y-1,p.z,Kind.TRIM); + put(p.x,y,p.z,Kind.FLOOR); + } + for(int dy=1;dy<=3;dy++) put(p.x,y+dy,p.z,Kind.AIR); + // Low parapets only along exposed bridge edges, never across the centre route. + boolean edge=Arrays.stream(Facing.values()).anyMatch(d->!deck.containsKey(new Cell(p.x+d.dx,p.z+d.dz))); + if(bridge && edge && !centerline.contains(p) && y-h>=3 && at>2 && at feet=new ArrayList<>(); + for(int i=0;i=ground(p.x,p.z)) { + Facing direction=direction(p,next); + put(p.x,y,p.z,Kind.STAIR,direction); + } + } + } + links.add(new Link(id,bridge,feet)); + } + } + private static Set strip(List route,int index) { + Cell p=route.get(index); + Set result=new LinkedHashSet<>(); result.add(p); + if(index>0) addSides(result,p,direction(route.get(index-1),p)); + if(index+1 result,Cell p,Facing tangent) { + result.add(new Cell(p.x-tangent.dz,p.z+tangent.dx)); + result.add(new Cell(p.x+tangent.dz,p.z-tangent.dx)); + } + private static Facing direction(Cell a,Cell b) { + for(Facing d:Facing.values()) if(a.x+d.dx==b.x && a.z+d.dz==b.z) return d; + throw new IllegalArgumentException("Non-adjacent path cells"); + } + private static List line(Cell a,Cell b) { + if(a.x!=b.x && a.z!=b.z) throw new IllegalArgumentException("Path segment must be axis aligned"); + List result=new ArrayList<>(); int dx=Integer.compare(b.x,a.x),dz=Integer.compare(b.z,a.z); + for(Cell p=a;;p=new Cell(p.x+dx,p.z+dz)) { result.add(p); if(p.equals(b)) break; } + return result; + } + private static void append(List target,List part) { + for(Cell p:part) if(target.isEmpty() || !target.getLast().equals(p)) target.add(p); + } + private TerracedCastlePlanner() {} +} diff --git a/core/src/test/java/dev/castleforge/core/TerracedVerification.java b/core/src/test/java/dev/castleforge/core/TerracedVerification.java new file mode 100644 index 0000000..d439066 --- /dev/null +++ b/core/src/test/java/dev/castleforge/core/TerracedVerification.java @@ -0,0 +1,119 @@ +package dev.castleforge.core; + +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; +import java.security.MessageDigest; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import static dev.castleforge.core.TerracedCastlePlanner.*; +import static dev.castleforge.core.CastlePlanner.Pos; + +/** Standalone deterministic/geometry regression gate. No Minecraft runtime is simulated here. */ +public final class TerracedVerification { + private static int assertions,accepted,rejected; + private static void check(boolean ok,String name) { + assertions++; if(!ok) throw new AssertionError(name); + } + private static void rejects(Runnable action,String name) { + boolean rejected=false; try { action.run(); } catch(IllegalArgumentException e) { rejected=true; } + check(rejected,name); + } + private static final String[] STYLES={"central_european","nordic","mediterranean","desert_citadel","east_asian","gothic","high_fantasy","maritime"}; + private static CultureMap.Region region(int i) { + return new CultureMap.Region("test",STYLES[i%STYLES.length],STYLES[(i+1)%STYLES.length],0,0,0,7168); + } + public static void main(String[] args) throws Exception { + long started=System.nanoTime(); + Ground flat=(x,z)->64; + List terrains=List.of(flat,(x,z)->80-Math.floorDiv(z,6),(x,z)->80+Math.floorDiv(x,5), + (x,z)->80-Math.floorDiv(z,7)-Math.floorDiv(Math.abs(x),18), + (x,z)->Math.abs(z)>=13 && Math.abs(z)<=15?58:64); + Set conditions=new HashSet<>(); Set rotations=new HashSet<>(); + Set roofs=new HashSet<>(); Set sizes=new HashSet<>(); int bridges=0,stairs=0; + for(int seed=0;seed<32;seed++) for(int terrain=0;terrain=31,"interior and walkway targets"); + conditions.add(p.condition()); rotations.add(p.quarterTurns()); sizes.add(p.blocks().size()); + if(p.links().stream().anyMatch(Link::bridge)) bridges++; + if(p.blocks().stream().anyMatch(b->b.kind()==Kind.STAIR)) stairs++; + for(Room room:p.rooms()) roofs.add(room.roof()); + boolean dependencies=false; int lastY=Integer.MIN_VALUE; Set coordinates=new HashSet<>(); + for(Block b:p.blocks()) { + check(coordinates.add(b.pos()),"unique coordinates"); + check(Math.abs(b.pos().x())<=RADIUS && Math.abs(b.pos().z())<=RADIUS,"finite survey footprint"); + check(b.pos().y()>=ground.surfaceY(b.pos().x(),b.pos().z()),"never excavate terrain"); + if(b.kind()==Kind.LADDER) dependencies=true; + else { + check(!dependencies,"all backing geometry precedes ladders"); + check(b.pos().y()>=lastY,"bottom-up structural placement"); lastY=b.pos().y(); + } + } + for(Terrace t:p.terraces()) check(t.maximumFill()<=MAX_FOUNDATION,"bounded terrace foundations"); + // Planner already ran navigation; repeat on an independently supplied terrain callback. + check(PlanNavigation.verify(p,ground).targets()==p.targets().size(),"all declared rooms and walks reachable"); + if(terrain==0) check(p.equals(plan(seed,0,0,flat,region(seed))),"same seed produces byte-equivalent plan order"); + } + check(bridges>=32,"ravines create pier-supported bridges"); + check(stairs>=80,"slopes create directional stairs"); + check(conditions.size()==3,"all condition states"); + check(rotations.size()==4,"all orientations"); + check(roofs.size()==4,"four roof grammars"); + check(sizes.size()>50,"multiple footprints and silhouettes"); + + AtomicInteger reads=new AtomicInteger(); + plan(42,0,0,(x,z)->{reads.incrementAndGet();return 64;},region(0)); + check(reads.get()==(2*RADIUS+1)*(2*RADIUS+1),"terrain read once; candidate retries only use immutable snapshot"); + rejects(()->plan(1,0,0,(x,z)->UNUSABLE,region(0)),"ocean or protected site rejected"); + rejects(()->plan(1,0,0,(x,z)->x<0?64:110,region(0)),"cliff rejected rather than buried"); + rejects(()->plan(1,0,0,(x,z)->x==0&&z==0?UNUSABLE:64,region(0)),"protected footprint rejected"); + check(!plan(1,0,0,(x,z)->x==RADIUS&&z==RADIUS?UNUSABLE:64,region(0)).blocks().isEmpty(),"unused bad terrain does not reject a valid site"); + rejects(()->plan(1,29_999_801,0,flat,region(0)),"world coordinate limit"); + rejects(()->plan(1,0,0,(x,z)->Integer.MAX_VALUE,region(0)),"invalid terrain height"); + rejects(()->plan(1,0,0,(x,z)->-1025,region(0)),"unsupported low terrain"); + for(int x:new int[]{-29_999_800,-7168,-1,29_999_800}) { + Plan p=plan(42,x,-x,flat,region(0)); + check(p.equals(plan(42,x,-x,flat,region(0))),"negative/edge coordinate stability"); + } + Plan reference=plan(42,0,0,flat,region(0)); + List broken=reference.blocks().stream().map(b->b.kind()==Kind.LADDER?new Block(b.pos(),Kind.AIR,b.facing()):b).toList(); + Plan disconnected=new Plan(broken,reference.terraces(),reference.rooms(),reference.links(),reference.targets(),reference.entrance(), + reference.quarterTurns(),reference.condition(),reference.region(),0,0); + rejects(()->PlanNavigation.verify(disconnected,flat),"missing vertical access must be rejected"); + List duplicates=new ArrayList<>(reference.blocks()); duplicates.add(duplicates.getFirst()); + Plan duplicate=new Plan(duplicates,reference.terraces(),reference.rooms(),reference.links(),reference.targets(),reference.entrance(), + reference.quarterTurns(),reference.condition(),reference.region(),0,0); + rejects(()->PlanNavigation.verify(duplicate,flat),"duplicate write sets rejected"); + try(ExecutorService workers=Executors.newFixedThreadPool(4)) { + List> futures=new ArrayList<>(); + for(int i=0;i<8;i++) futures.add(workers.submit(()->plan(42,0,0,flat,region(0)))); + for(Future future:futures) check(reference.equals(future.get()),"parallel planning has no shared RNG state"); + } + String digest=digest(reference); + check(digest.equals("6fd20d8855fdc190a7e81e9772cef9d4aad3974a3a405ca25f31161b643f7828"),"frozen geometry contract v1"); + System.out.println("Reference SHA-256: "+digest); + if(args.length>0) export(reference,Path.of(args[0])); + System.out.printf(Locale.ROOT,"PASS terraced: %d accepted reference sites, %d unexpected rejections, %d bridges, %d stair sites; %d invariant assertions; %.2f s.%n", + accepted,rejected,bridges,stairs,assertions,(System.nanoTime()-started)/1e9); + } + private static String digest(Plan p) throws Exception { + MessageDigest digest=MessageDigest.getInstance("SHA-256"); + for(Block b:p.blocks()) digest.update((b.toString()+"\n").getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest.digest()); + } + private static void export(Plan p,Path path) throws Exception { + Files.createDirectories(path.toAbsolutePath().getParent()); + try(var writer=Files.newBufferedWriter(path)) { + writer.write("x,y,z,kind,facing\n"); + for(Block b:p.blocks()) writer.write(b.pos().x()+","+b.pos().y()+","+b.pos().z()+","+b.kind()+","+b.facing()+"\n"); + } + } + private TerracedVerification() {} +} diff --git a/docs/TERRACED_ARCHITECTURE.md b/docs/TERRACED_ARCHITECTURE.md new file mode 100644 index 0000000..1956f3c --- /dev/null +++ b/docs/TERRACED_ARCHITECTURE.md @@ -0,0 +1,57 @@ +# Terraced architecture v1 — 0.2.0-alpha.1 + +## Scope and separation + +The classic `CastlePlanner`, `CultureMap` and `WorldSettings` contracts are unchanged. `TerracedCastlePlanner` is an opt-in, bounded manual reference design, selected with `/castleforge preview terraced [x z]`. It does not register automatic world generation. Architecture version 1 and culture version 1 are separate contracts. + +This step demonstrates one asymmetric, three-court composition with eight modules. It does not yet grow arbitrary shapes around every mountain, implement settlements, or claim compatibility with all world generators. Terrain that cannot safely accommodate the reference composition is rejected. Building designs are procedural project code, not imported schematics. + +## Pipeline + +1. The adapter requires moderator permission, Overworld, and already-loaded survey chunks. +2. Capture exactly 105 × 105 column samples once, on the server thread. Unknown, wet or non-whitelisted ground is marked unusable. Unused bad columns need not reject the site. +3. Evaluate four cardinal orientations of seed-derived, offset courtyard footprints. Score foundation volume and prefer the keep uphill of the entrance. No additional world reads are needed for retries. +4. Establish an individual floor for each court. No planned cell may be below the sampled first-free height; excavation is prohibited. Local foundation depth is limited to eight blocks and inter-court floor relief to 24 blocks. These are rejection limits, not a claim that every such slope is accepted. +5. Place halls, towers, keep and gatehouse within the enclosure system. The rooms, storeys, roof family and construction phase are recorded explicitly. Geometry remains one reference grammar; culture affects palettes and selected roof rules. +6. Plan three-wide connector footprints, solve a slope-limited height profile, add steps and short beam/pier sections. Pier depth is limited to twelve blocks. Some exposed bridge footprint cells become parapets; clear walking width can be narrower. +7. Generate weathering in spatial patches. Keep doorways, ladders, access floors and supports protected. Ruined variants remove selected crenels/glazing; realistic collapse and repair simulation remain future work. +8. Verify two-block clearance and conservative walking/jumping/ladder reachability to every declared interior floor and all four enclosure sides. Navigation is bounded to 100,000 visited positions. Stair geometry is conservatively treated as full cubes; this is not a replacement for real game tests. +9. Sort structural writes bottom-up, then attach ladders after every backing wall is present. Directional blocks rotate with the layout. +10. The Fabric adapter validates height/border/replaceability, keeps a 120-second preview and requires `build confirm`. No-op air cells and sampled support blocks are rechecked too. During placement the existing per-edit conflict checks, cancel and session-only undo remain active. + +## Data and budgets + +- `Plan`: immutable blocks, terraces, rooms, links and navigation targets; world seed influences the plan without mutable global RNG. +- `Terrace` / `Room` rectangles are local coordinates. Block positions, entrance and navigation targets are world coordinates. The plan records its rotation and origin to avoid ambiguity. +- `Room.phase`: 0 oldest core, 1 expansion, 2 repaired/newer work. Phase affects weathering; it is deliberately not advertised as a full historical simulation. +- Maximum 180,000 final cells, deduplicated. Typical reference fixtures are much smaller. The limit includes planned AIR cells. +- Planning is synchronous and suitable only for this bounded prototype. Large monuments need asynchronous pure planning and proper chunk-local worldgen integration rather than simply increasing these constants. +- No claim/protection-mod integration; vanilla-looking player-built ground cannot be distinguished reliably from natural ground. Only disposable test worlds are supported for acceptance work. + +## Verification performed by the new suite + +32 seeds × five terrain fixtures: flat, northward slope, eastward slope, ridge slope and short transverse gullies. In the recorded local run all 160 combinations succeeded; 100 plans included a bridge section and 96 included directional steps. Additional cases cover protected/water-like terrain, cliffs, invalid heights, unused invalid survey corners, coordinate edges, missing vertical access, duplicate cells, fixed sampling count, deterministic replays and parallel generation. + +The flat central-European reference geometry at seed 42 and origin 0,0 is frozen by SHA-256: + +```text +6fd20d8855fdc190a7e81e9772cef9d4aad3974a3a405ca25f31161b643f7828 +``` + +The new suite passed locally on Java 21 with a 512 MiB heap. CI additionally compiles the real Fabric adapter and runs both generator suites. The PR checks are the source of truth for CI status; this document does not predeclare their result. + +## In-game acceptance still required + +- [ ] Start the exact 26.1.2 Fabric instance and a dedicated server without runtime registration errors. +- [ ] Confirm `/castleforge preview` still selects the classic generator. +- [ ] Confirm `/castleforge preview terraced` is read-only and displays three courts/eight modules. +- [ ] Complete a superflat build; enter the gatehouse, all building storeys and every wall-walk side without flying. +- [ ] Repeat in a new disposable normal world on a gradual open slope and a suitable short gully. +- [ ] Check roof/stair orientation and ladder persistence in all four rotations after neighbor updates. +- [ ] Check the doorway/interior clearance in restored, weathered and ruined variants using actual player movement. +- [ ] Put a block in a previously empty doorway between preview and confirmation; confirmation must refuse before writing. +- [ ] Test cancel, conflict-aware undo, automatic stair-shape changes, unloaded-site pause/resume and documented history loss after world close. +- [ ] Inspect visual scale, material transitions, underside supports and bridge entrances; pure geometry tests cannot certify their appearance. +- [ ] Record real preview stalls, generation tick cost and rendering performance before making performance claims. + +Existing worlds, other terrain/structure/claim mods, Bedrock/consoles, giant monuments and automatic worldgen remain unverified or unimplemented. Do not install this alpha into a valuable survival save. diff --git a/fabric/src/main/java/dev/castleforge/fabric/CastleForge.java b/fabric/src/main/java/dev/castleforge/fabric/CastleForge.java index c7e5cb8..38006a6 100644 --- a/fabric/src/main/java/dev/castleforge/fabric/CastleForge.java +++ b/fabric/src/main/java/dev/castleforge/fabric/CastleForge.java @@ -2,6 +2,7 @@ import dev.castleforge.core.CastlePlanner; import dev.castleforge.core.CultureMap; +import dev.castleforge.core.TerracedCastlePlanner; import com.mojang.brigadier.arguments.IntegerArgumentType; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; @@ -18,6 +19,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.StairBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.Heightmap; import org.slf4j.Logger; @@ -37,13 +39,20 @@ public final class CastleForge implements ModInitializer { CommandRegistrationCallback.EVENT.register((dispatcher, registry, environment) -> dispatcher.register( Commands.literal("castleforge") .requires(s -> s.permissions().hasPermission(Permissions.COMMANDS_MODERATOR)) - .executes(c -> say(c.getSource(), "CastleForge alpha: /castleforge region | preview [x z] | build confirm | status | cancel | undo. TEST WORLDS ONLY.")) + .executes(c -> say(c.getSource(), "CastleForge alpha: /castleforge region | preview [terraced] [x z] | build confirm | status | cancel | undo. TEST WORLDS ONLY.")) .then(Commands.literal("region").executes(c -> safely(c.getSource(), () -> region(c.getSource())))) - .then(Commands.literal("preview").executes(c -> safely(c.getSource(), () -> preview(c.getSource(), null, null))) + .then(Commands.literal("preview") + .executes(c -> safely(c.getSource(), () -> preview(c.getSource(), null, null, false))) .then(Commands.argument("x", IntegerArgumentType.integer(-29_999_800, 29_999_800)) .then(Commands.argument("z", IntegerArgumentType.integer(-29_999_800, 29_999_800)) .executes(c -> safely(c.getSource(), () -> preview(c.getSource(), - IntegerArgumentType.getInteger(c,"x"), IntegerArgumentType.getInteger(c,"z"))))))) + IntegerArgumentType.getInteger(c,"x"), IntegerArgumentType.getInteger(c,"z"), false))))) + .then(Commands.literal("terraced") + .executes(c -> safely(c.getSource(), () -> preview(c.getSource(), null, null, true))) + .then(Commands.argument("x", IntegerArgumentType.integer(-29_999_800, 29_999_800)) + .then(Commands.argument("z", IntegerArgumentType.integer(-29_999_800, 29_999_800)) + .executes(c -> safely(c.getSource(), () -> preview(c.getSource(), + IntegerArgumentType.getInteger(c,"x"), IntegerArgumentType.getInteger(c,"z"), true))))))) .then(Commands.literal("build").then(Commands.literal("confirm") .executes(c -> safely(c.getSource(), () -> build(c.getSource()))))) .then(Commands.literal("status").executes(c -> safely(c.getSource(), () -> status(c.getSource())))) @@ -82,7 +91,7 @@ private int region(CommandSourceStack source) throws IOException { return say(source, "Culture " + r.style() + " / " + r.id() + "; nominal spacing " + r.nominalSpacing() + " blocks; border blend " + Math.round(r.borderBlend()*100) + "%. Scale uses a configured reference, not automatic biome measurement."); } - private int preview(CommandSourceStack source, Integer x, Integer z) throws IOException { + private int preview(CommandSourceStack source, Integer x, Integer z, boolean terraced) throws IOException { ServerLevel level = source.getLevel(); overworld(level); Session s = session(source); if (s.job != null && !s.job.finished) throw new IllegalArgumentException("A placement or undo is already running."); @@ -91,36 +100,62 @@ private int preview(CommandSourceStack source, Integer x, Integer z) throws IOEx s.previews.entrySet().removeIf(e -> System.nanoTime() - e.getValue().created > PREVIEW_LIFETIME_NS); if (s.previews.size() >= 8) throw new IllegalArgumentException("Too many previews; try after another preview expires."); BlockPos p = BlockPos.containing(source.getPosition()); + int radius = terraced ? TerracedCastlePlanner.RADIUS : CastlePlanner.RADIUS; int ox = x == null ? p.getX() : x; - int oz = z == null ? p.getZ() - CastlePlanner.RADIUS - 4 : z; - int radius = CastlePlanner.RADIUS; + int oz = z == null ? p.getZ() - radius - 4 : z; + if (Math.abs((long)ox) > 29_999_800 || Math.abs((long)oz) > 29_999_800) + throw new IllegalArgumentException("Site too near world coordinate limit."); for (int cx = (ox-radius)>>4; cx <= (ox+radius)>>4; cx++) for (int cz = (oz-radius)>>4; cz <= (oz+radius)>>4; cz++) if (!level.getChunkSource().hasChunk(cx,cz)) throw new IllegalArgumentException("Entire site must already be loaded. Walk nearer; no chunks are force-generated."); var region = s.settings.map(level.getSeed()).at(ox,oz); - var plan = CastlePlanner.plan(level.getSeed(), ox, oz, (px,pz) -> { + BlockState centerGround = level.getBlockState(new BlockPos(ox,level.getHeight(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES,ox,oz)-1,oz)); + Palette palette = Palette.choose(region.style(), centerGround.is(Blocks.SAND) || centerGround.is(Blocks.RED_SAND) || centerGround.is(Blocks.SANDSTONE)); + List checks = new ArrayList<>(); + TerracedCastlePlanner.Ground ground = (px,pz) -> { int y = level.getHeight(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES,px,pz); - BlockState ground = level.getBlockState(new BlockPos(px,y-1,pz)); - if (!ground.getFluidState().isEmpty() || !naturalGround(ground)) + BlockPos pos = new BlockPos(px,y-1,pz); + BlockState state = level.getBlockState(pos); + checks.add(new Check(pos,state)); + if (!state.getFluidState().isEmpty() || !naturalGround(state)) { + if (terraced) return TerracedCastlePlanner.UNUSABLE; throw new IllegalArgumentException("Unsuitable ground, water or existing structure at " + px + "," + pz); + } return y; - }, region); - BlockState ground = level.getBlockState(new BlockPos(ox,level.getHeight(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES,ox,oz)-1,oz)); - Palette palette = Palette.choose(region.style(), ground.is(Blocks.SAND) || ground.is(Blocks.RED_SAND) || ground.is(Blocks.SANDSTONE)); + }; + List desired = new ArrayList<>(); + String summary; + if (terraced) { + var plan = TerracedCastlePlanner.plan(level.getSeed(),ox,oz,ground,region); + for (var block : plan.blocks()) { + var v = block.pos(); desired.add(new Desired(new BlockPos(v.x(),v.y(),v.z()),palette.resolve(block))); + } + summary = "TERRACED v1 / " + plan.condition() + "; " + plan.terraces().size() + " courts, " + + plan.rooms().size() + " modules, " + plan.targets().size() + " verified access targets; terrace relief " + + plan.relief() + "; rotation " + (plan.quarterTurns()*90) + " degrees"; + } else { + var plan = CastlePlanner.plan(level.getSeed(),ox,oz,ground::surfaceY,region); + for (var voxel : plan.voxels()) { + var v = voxel.pos(); desired.add(new Desired(new BlockPos(v.x(),v.y(),v.z()),palette.resolve(voxel.material()))); + } + summary = "CLASSIC / " + plan.condition() + "; relief " + plan.relief(); + } List edits = new ArrayList<>(); - for (var voxel : plan.voxels()) { - var v = voxel.pos(); BlockPos pos = new BlockPos(v.x(),v.y(),v.z()); + for (Desired cell : desired) { + BlockPos pos = cell.pos; if (level.isOutsideBuildHeight(pos) || !level.getWorldBorder().isWithinBounds(pos)) throw new IllegalArgumentException("Plan exceeds build height or world border."); - BlockState before = level.getBlockState(pos), after = palette.resolve(voxel.material()); + BlockState before = level.getBlockState(pos), after = cell.state; if (level.getBlockEntity(pos) != null || !before.getFluidState().isEmpty() || !replaceable(before)) throw new IllegalArgumentException("Protected or non-natural block at " + pos.toShortString() + ". Nothing was changed."); + // Include unchanged air: a newly obstructed doorway must invalidate confirmation too. + checks.add(new Check(pos,before)); if (!before.equals(after)) edits.add(new Edit(pos,before,after)); } - s.previews.put(user,new Preview(level,List.copyOf(edits),plan,System.nanoTime())); - LOGGER.info("CastleForge preview {} at {},{}: {} edits, {}", user,ox,oz,edits.size(),plan.condition()); - return say(source,"PREVIEW only: " + region.style() + " / " + plan.condition() + " at " + ox + "," + plan.floorY() + "," + oz - + "; " + edits.size() + " edits; relief " + plan.relief() + ". /castleforge build confirm within 120s. Back up first; use a throwaway world."); + s.previews.put(user,new Preview(level,List.copyOf(edits),List.copyOf(checks),System.nanoTime())); + LOGGER.info("CastleForge preview {} at {},{}: {} edits; {}",user,ox,oz,edits.size(),summary); + return say(source,"PREVIEW only: " + region.style() + " at " + ox + "," + oz + "; " + summary + "; " + + edits.size() + " edits. /castleforge build confirm within 120s. Disposable test world only; back up first."); } private int build(CommandSourceStack source) throws IOException { Session s = session(source); @@ -128,8 +163,8 @@ private int build(CommandSourceStack source) throws IOException { Preview p = s.previews.remove(owner(source)); if (p == null || System.nanoTime() - p.created > PREVIEW_LIFETIME_NS || p.level != source.getLevel()) throw new IllegalArgumentException("Run a fresh preview in this dimension first."); - for (Edit e : p.edits) { - if (!loaded(p.level,e.pos) || !p.level.getBlockState(e.pos).equals(e.before) || p.level.getBlockEntity(e.pos)!=null) + for (Check check : p.checks) { + if (!loaded(p.level,check.pos) || !p.level.getBlockState(check.pos).equals(check.expected) || p.level.getBlockEntity(check.pos)!=null) throw new IllegalArgumentException("Site changed since preview; nothing was placed. Preview again."); } s.job = new Job(owner(source), source, p.level, p.edits, false); @@ -177,8 +212,16 @@ private static int safely(CommandSourceStack source, Action action) { catch (IllegalArgumentException | IOException e) { source.sendFailure(Component.literal("CastleForge: " + e.getMessage())); return 0; } catch (RuntimeException e) { LOGGER.error("CastleForge command failed",e); source.sendFailure(Component.literal("CastleForge failed; see server log. No automatic retry.")); return 0; } } + private record Desired(BlockPos pos, BlockState state) {} + private record Check(BlockPos pos, BlockState expected) {} private record Edit(BlockPos pos, BlockState before, BlockState after) {} - private record Preview(ServerLevel level, List edits, CastlePlanner.Plan plan, long created) {} + private record Preview(ServerLevel level, List edits, List checks, long created) {} + private static boolean matchesUndo(BlockState actual, BlockState expected) { + // Neighbor updates recompute stair shape; never ignore facing, half, material or waterlogging changes. + if (expected.getBlock() instanceof StairBlock && actual.is(expected.getBlock())) + return actual.setValue(StairBlock.SHAPE, expected.getValue(StairBlock.SHAPE)).equals(expected); + return actual.equals(expected); + } private static final class Session { final WorldSettings settings; final Map previews = new HashMap<>(); Job job, lastBuild; @@ -203,10 +246,16 @@ void tick() { } unloadedTicks=0; BlockState expected = undo ? e.after : e.before, target = undo ? e.before : e.after; - if (level.getBlockEntity(e.pos)!=null || !level.getBlockState(e.pos).equals(expected)) { + BlockState actual = level.getBlockState(e.pos); + boolean matches = undo ? matchesUndo(actual,expected) : actual.equals(expected) + || (expected.canBeReplaced() && actual.isAir()); + if (level.getBlockEntity(e.pos)!=null || !matches) { if (undo) { conflicts++; index++; work++; continue; } finished=true; message="Stopped: world changed at " + e.pos.toShortString() + ". Partial build remains; use undo."; say(source,message); return; } + // Neighbor updates may already have cleared replaceable vegetation to the target air. + // Do not treat a no-op setBlock result as failure or claim it as our own applied edit. + if (actual.equals(target)) { index++; work++; continue; } if (!level.setBlock(e.pos,target,Block.UPDATE_ALL)) { if (undo) { conflicts++; index++; work++; continue; } finished=true; message="Stopped: placement rejected. Use undo for the partial build."; say(source,message); return; diff --git a/fabric/src/main/java/dev/castleforge/fabric/Palette.java b/fabric/src/main/java/dev/castleforge/fabric/Palette.java index b35349e..224af8e 100644 --- a/fabric/src/main/java/dev/castleforge/fabric/Palette.java +++ b/fabric/src/main/java/dev/castleforge/fabric/Palette.java @@ -1,10 +1,12 @@ package dev.castleforge.fabric; import dev.castleforge.core.CastlePlanner.Material; +import dev.castleforge.core.TerracedCastlePlanner; import net.minecraft.core.Direction; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.LadderBlock; +import net.minecraft.world.level.block.StairBlock; import net.minecraft.world.level.block.state.BlockState; /** Vanilla-only prototype palettes. Full cultural building grammars are a later milestone. */ @@ -34,4 +36,34 @@ BlockState resolve(Material material) { case LADDER_SOUTH -> Blocks.LADDER.defaultBlockState().setValue(LadderBlock.FACING, Direction.SOUTH); }; } + BlockState resolve(TerracedCastlePlanner.Block block) { + Direction facing = Direction.valueOf(block.facing().name()); + return switch (block.kind()) { + case AIR -> Blocks.AIR.defaultBlockState(); + case FOUNDATION, WALL, TRIM -> masonry.defaultBlockState(); + case WEATHERED -> weathered.defaultBlockState(); + case FLOOR -> floor.defaultBlockState(); + case ROOF -> roof.defaultBlockState(); + case TIMBER -> Blocks.STRIPPED_SPRUCE_LOG.defaultBlockState(); + case GLASS -> Blocks.GLASS.defaultBlockState(); + case LIGHT -> Blocks.GLOWSTONE.defaultBlockState(); + case STAIR -> stairs(masonry).defaultBlockState().setValue(StairBlock.FACING, facing); + case ROOF_STAIR -> stairs(roof).defaultBlockState().setValue(StairBlock.FACING, facing); + case LADDER -> Blocks.LADDER.defaultBlockState().setValue(LadderBlock.FACING, facing); + }; + } + private static Block stairs(Block block) { + if (block == Blocks.SANDSTONE || block == Blocks.TERRACOTTA) return Blocks.SANDSTONE_STAIRS; + if (block == Blocks.COBBLESTONE) return Blocks.COBBLESTONE_STAIRS; + if (block == Blocks.DARK_OAK_PLANKS) return Blocks.DARK_OAK_STAIRS; + if (block == Blocks.SPRUCE_PLANKS) return Blocks.SPRUCE_STAIRS; + if (block == Blocks.RED_NETHER_BRICKS) return Blocks.RED_NETHER_BRICK_STAIRS; + if (block == Blocks.DEEPSLATE_TILES) return Blocks.DEEPSLATE_TILE_STAIRS; + if (block == Blocks.DEEPSLATE_BRICKS) return Blocks.DEEPSLATE_BRICK_STAIRS; + if (block == Blocks.QUARTZ_BRICKS) return Blocks.QUARTZ_STAIRS; + if (block == Blocks.PURPUR_BLOCK) return Blocks.PURPUR_STAIRS; + if (block == Blocks.DARK_PRISMARINE) return Blocks.DARK_PRISMARINE_STAIRS; + return Blocks.STONE_BRICK_STAIRS; + } + } diff --git a/scripts/verify-core.sh b/scripts/verify-core.sh index c597249..98372e5 100755 --- a/scripts/verify-core.sh +++ b/scripts/verify-core.sh @@ -6,3 +6,4 @@ mkdir -p "$output" find core/src/main/java core/src/test/java -name '*.java' -print > "$output/sources.txt" javac --release 21 -d "$output" @"$output/sources.txt" java -Xmx512m -cp "$output" dev.castleforge.core.CoreVerification +java -Xmx512m -cp "$output" dev.castleforge.core.TerracedVerification