@threenative/procedural-environment 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -50,6 +50,10 @@ interface IBakeCityOptions {
50
50
  readonly curb?: boolean;
51
51
  /** Include lane paint on straight and curve modules. Default true. */
52
52
  readonly markings?: boolean;
53
+ /** Light canvas-drawn sign materials (`extras.sign`) with an emissive map for night scenes. Default false. */
54
+ readonly emissiveSigns?: boolean;
55
+ /** Convert transmissive architectural glass (`transmission > 0`) to opaque reflective PBR glass so background buildings avoid a full-scene transmission pass. Default false. */
56
+ readonly opaqueGlass?: boolean;
53
57
  }
54
58
 
55
59
  interface IVegetationPreset {
@@ -299,10 +303,13 @@ declare function bakeRock(options: IBakeRockOptions): Promise<IEnvironmentBake[]
299
303
  * @constraint units are metres, +Y up; stock roads fit a 24 m grid, and custom straights and bends export updated socket positions, directions, widths and lane centres in the root node's extras
300
304
  * @constraint roadWidth and markings apply to straight and curve; roadLength applies to straight; bendAngle, bendRadius and bendSide apply to curve; roadSurface applies to socketed road modules
301
305
  * @constraint bake-time only, so keep it a dev dependency; textures are capped at 1024 px like the page's export
306
+ * @constraint only bake road tiles (`straight`, `curve`, `cross`, `tee`, `alley`, `grid`, `pit`, `cul-de-sac`) when assembling the drivable carriageway from kit tiles; when a level builds its own spline or terrain road, bake scenery modules instead (`detail: 1, dressing: false` keeps draw counts low)
307
+ * @constraint `emissiveSigns: true` lights canvas-drawn signs (`extras.sign`) for night scenes; `opaqueGlass: true` converts transmissive architectural glass to opaque reflective PBR glass so background buildings avoid a full-scene transmission pass
302
308
  * @requires npm i -D @threenative/procedural-environment
303
- * @example await bakeCity({ module: "cross", out: "assets/city" });
304
- * @example await bakeCity({ module: "curve", bendAngle: 55, bendRadius: 24, bendSide: "left", roadWidth: 12, sidewalk: false, curb: false, out: "assets/city" });
305
- * @example await bakeCity({ module: "apartments", seed: 7, floors: 8, out: "assets/city" });
309
+ * @example await bakeCity({ module: "office", detail: 1, dressing: false, out: "assets/city" });
310
+ * @example await bakeCity({ module: "civic-ad", detail: 1, text: "GRAND PRIX", emissiveSigns: true, out: "assets/city" });
311
+ * @example // Modular-road layout built from kit tiles:
312
+ * await bakeCity({ module: "cross", out: "assets/city" });
306
313
  */
307
314
  declare function bakeCity(options: IBakeCityOptions): Promise<IEnvironmentBake[]>;
308
315
 
package/dist/index.js CHANGED
@@ -4276,6 +4276,10 @@ var cityRoadDefaults = {
4276
4276
  curb: true,
4277
4277
  markings: true
4278
4278
  };
4279
+ var cityBakeDefaults = {
4280
+ emissiveSigns: false,
4281
+ opaqueGlass: false
4282
+ };
4279
4283
  var cityRoadEdgeModules = [
4280
4284
  "straight",
4281
4285
  "curve",
@@ -4429,6 +4433,307 @@ function roadSettings(options, hasSockets) {
4429
4433
  }
4430
4434
  return road;
4431
4435
  }
4436
+ var MATERIAL_TEXTURE_SLOTS = [
4437
+ "map",
4438
+ "normalMap",
4439
+ "roughnessMap",
4440
+ "metalnessMap",
4441
+ "aoMap",
4442
+ "emissiveMap",
4443
+ "alphaMap",
4444
+ "bumpMap",
4445
+ "clearcoatMap",
4446
+ "clearcoatNormalMap",
4447
+ "clearcoatRoughnessMap",
4448
+ "transmissionMap",
4449
+ "thicknessMap",
4450
+ "specularColorMap",
4451
+ "specularIntensityMap"
4452
+ ];
4453
+ function bakeSettings(options) {
4454
+ const settings = {
4455
+ emissiveSigns: options.emissiveSigns ?? cityBakeDefaults.emissiveSigns,
4456
+ opaqueGlass: options.opaqueGlass ?? cityBakeDefaults.opaqueGlass
4457
+ };
4458
+ if (typeof settings.emissiveSigns !== "boolean")
4459
+ throw new Error(
4460
+ `bakeCity: emissiveSigns must be true or false, got ${JSON.stringify(settings.emissiveSigns)}`
4461
+ );
4462
+ if (typeof settings.opaqueGlass !== "boolean")
4463
+ throw new Error(
4464
+ `bakeCity: opaqueGlass must be true or false, got ${JSON.stringify(settings.opaqueGlass)}`
4465
+ );
4466
+ const changes = Object.entries(settings).filter(
4467
+ ([key, value]) => cityBakeDefaults[key] !== value
4468
+ );
4469
+ return { changes, settings };
4470
+ }
4471
+ function applyMaterialOptions(material, bake) {
4472
+ if (bake.emissiveSigns && material.userData?.sign === true && material.map) {
4473
+ if (!material.emissiveMap) {
4474
+ material.emissiveMap = material.map;
4475
+ material.emissive?.setRGB?.(1, 1, 1);
4476
+ }
4477
+ if (typeof material.emissiveIntensity !== "number" || material.emissiveIntensity <= 0) {
4478
+ material.emissiveIntensity = 1;
4479
+ }
4480
+ }
4481
+ if (bake.opaqueGlass && typeof material.transmission === "number" && material.transmission > 0) {
4482
+ material.transmission = 0;
4483
+ if (typeof material.thickness === "number") material.thickness = 0;
4484
+ }
4485
+ }
4486
+ function applyCityMaterialOptions(group, bake) {
4487
+ if (!bake.emissiveSigns && !bake.opaqueGlass) return;
4488
+ const seen = /* @__PURE__ */ new Set();
4489
+ group.traverse((object) => {
4490
+ const mesh = object;
4491
+ if (mesh.isMesh !== true) return;
4492
+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
4493
+ for (const material of materials) {
4494
+ if (material === void 0 || material === null || seen.has(material)) continue;
4495
+ seen.add(material);
4496
+ applyMaterialOptions(material, bake);
4497
+ }
4498
+ });
4499
+ }
4500
+ function imageSignature(image, cache, fallbackIds) {
4501
+ if (image === void 0 || image === null || typeof image !== "object") return "none";
4502
+ const existing = cache.get(image);
4503
+ if (existing !== void 0) return existing;
4504
+ let signature;
4505
+ if (typeof image.encodeSync === "function") {
4506
+ signature = `png:${createHash("sha256").update(image.encodeSync("png")).digest("hex")}`;
4507
+ } else if (image.data !== void 0 && ArrayBuffer.isView(image.data)) {
4508
+ const view = image.data;
4509
+ const hash = createHash("sha256").update(Buffer.from(view.buffer, view.byteOffset, view.byteLength)).digest("hex");
4510
+ signature = `raw:${image.width ?? 0}x${image.height ?? 0}:${hash}`;
4511
+ } else if (typeof image.src === "string" && image.src.length > 0) {
4512
+ signature = `src:${createHash("sha256").update(image.src).digest("hex")}`;
4513
+ } else {
4514
+ let id = fallbackIds.get(image);
4515
+ if (id === void 0) {
4516
+ id = fallbackIds.size;
4517
+ fallbackIds.set(image, id);
4518
+ }
4519
+ signature = `ref:${id}`;
4520
+ }
4521
+ cache.set(image, signature);
4522
+ return signature;
4523
+ }
4524
+ function textureSignature(texture, imageCache, fallbackImages) {
4525
+ return JSON.stringify({
4526
+ anisotropy: texture.anisotropy,
4527
+ center: texture.center ? [texture.center.x, texture.center.y] : void 0,
4528
+ channel: texture.channel,
4529
+ colorSpace: texture.colorSpace,
4530
+ flipY: texture.flipY,
4531
+ generateMipmaps: texture.generateMipmaps,
4532
+ image: imageSignature(texture.image, imageCache, fallbackImages),
4533
+ magFilter: texture.magFilter,
4534
+ minFilter: texture.minFilter,
4535
+ name: texture.name,
4536
+ offset: texture.offset ? [texture.offset.x, texture.offset.y] : void 0,
4537
+ premultiplyAlpha: texture.premultiplyAlpha,
4538
+ repeat: texture.repeat ? [texture.repeat.x, texture.repeat.y] : void 0,
4539
+ rotation: texture.rotation,
4540
+ unpackAlignment: texture.unpackAlignment,
4541
+ userData: texture.userData,
4542
+ wrapS: texture.wrapS,
4543
+ wrapT: texture.wrapT
4544
+ });
4545
+ }
4546
+ function materialSignature(material, canonicalTextureId) {
4547
+ const rgb = (c) => c === void 0 ? void 0 : [c.r, c.g, c.b];
4548
+ const vec2 = (v) => v === void 0 ? void 0 : [v.x, v.y];
4549
+ const slots = {};
4550
+ for (const slot of MATERIAL_TEXTURE_SLOTS) {
4551
+ const tex = material[slot];
4552
+ if (tex !== void 0 && tex !== null) slots[slot] = canonicalTextureId(tex);
4553
+ }
4554
+ return JSON.stringify({
4555
+ alphaTest: material.alphaTest,
4556
+ aoMapIntensity: material.aoMapIntensity,
4557
+ attenuationColor: rgb(material.attenuationColor),
4558
+ attenuationDistance: material.attenuationDistance,
4559
+ bumpScale: material.bumpScale,
4560
+ clearcoat: material.clearcoat,
4561
+ clearcoatNormalScale: vec2(material.clearcoatNormalScale),
4562
+ clearcoatRoughness: material.clearcoatRoughness,
4563
+ color: rgb(material.color),
4564
+ depthTest: material.depthTest,
4565
+ depthWrite: material.depthWrite,
4566
+ emissive: rgb(material.emissive),
4567
+ emissiveIntensity: material.emissiveIntensity,
4568
+ envMapIntensity: material.envMapIntensity,
4569
+ flatShading: material.flatShading,
4570
+ ior: material.ior,
4571
+ iridescence: material.iridescence,
4572
+ iridescenceIOR: material.iridescenceIOR,
4573
+ metalness: material.metalness,
4574
+ name: material.name,
4575
+ normalScale: vec2(material.normalScale),
4576
+ opacity: material.opacity,
4577
+ roughness: material.roughness,
4578
+ sheen: material.sheen,
4579
+ sheenColor: rgb(material.sheenColor),
4580
+ sheenRoughness: material.sheenRoughness,
4581
+ side: material.side,
4582
+ slots,
4583
+ specularColor: rgb(material.specularColor),
4584
+ specularIntensity: material.specularIntensity,
4585
+ thickness: material.thickness,
4586
+ transmission: material.transmission,
4587
+ transparent: material.transparent,
4588
+ type: material.type,
4589
+ userData: material.userData,
4590
+ vertexColors: material.vertexColors,
4591
+ wireframe: material.wireframe
4592
+ });
4593
+ }
4594
+ function dedupeCityMaterials(group) {
4595
+ const imageCache = /* @__PURE__ */ new Map();
4596
+ const fallbackImages = /* @__PURE__ */ new Map();
4597
+ const canonicalTextures = /* @__PURE__ */ new Map();
4598
+ const textureIds = /* @__PURE__ */ new Map();
4599
+ const canonicalizeTexture = (texture) => {
4600
+ const key = textureSignature(texture, imageCache, fallbackImages);
4601
+ let entry = canonicalTextures.get(key);
4602
+ if (entry === void 0) {
4603
+ entry = { id: canonicalTextures.size, texture };
4604
+ canonicalTextures.set(key, entry);
4605
+ textureIds.set(entry.texture, entry.id);
4606
+ }
4607
+ return entry.texture;
4608
+ };
4609
+ const textureId = (texture) => texture === void 0 || texture === null ? null : textureIds.get(texture) ?? null;
4610
+ const canonicalMaterials = /* @__PURE__ */ new Map();
4611
+ const materialIds = /* @__PURE__ */ new Map();
4612
+ const canonicalizeMaterial = (material) => {
4613
+ for (const slot of MATERIAL_TEXTURE_SLOTS) {
4614
+ const value = material[slot];
4615
+ if (value !== void 0 && value !== null) {
4616
+ material[slot] = canonicalizeTexture(value);
4617
+ }
4618
+ }
4619
+ const key = materialSignature(material, textureId);
4620
+ let entry = canonicalMaterials.get(key);
4621
+ if (entry === void 0) {
4622
+ entry = { id: canonicalMaterials.size, material };
4623
+ canonicalMaterials.set(key, entry);
4624
+ materialIds.set(entry.material, entry.id);
4625
+ }
4626
+ return entry.material;
4627
+ };
4628
+ group.traverse((object) => {
4629
+ const mesh = object;
4630
+ if (mesh.isMesh !== true) return;
4631
+ if (Array.isArray(mesh.material)) {
4632
+ mesh.material = mesh.material.map(
4633
+ (material) => material ? canonicalizeMaterial(material) : material
4634
+ );
4635
+ } else if (mesh.material) {
4636
+ mesh.material = canonicalizeMaterial(mesh.material);
4637
+ }
4638
+ });
4639
+ return materialIds;
4640
+ }
4641
+ function hasIdentityLocalTransform(object) {
4642
+ return object.position.x === 0 && object.position.y === 0 && object.position.z === 0 && object.quaternion.x === 0 && object.quaternion.y === 0 && object.quaternion.z === 0 && object.quaternion.w === 1 && object.scale.x === 1 && object.scale.y === 1 && object.scale.z === 1;
4643
+ }
4644
+ function geometryLayoutSignature(geometry) {
4645
+ if (geometry.groups.length > 0) return void 0;
4646
+ if (geometry.drawRange.start !== 0 || geometry.drawRange.count !== Number.POSITIVE_INFINITY)
4647
+ return void 0;
4648
+ if (geometry.morphAttributes !== void 0 && Object.keys(geometry.morphAttributes).length > 0)
4649
+ return void 0;
4650
+ const names = Object.keys(geometry.attributes).sort();
4651
+ if (names.length === 0) return void 0;
4652
+ const parts = [geometry.index !== null ? "idx" : "flat"];
4653
+ for (const name of names) {
4654
+ const attr = geometry.attributes[name];
4655
+ if (attr === void 0 || attr.isInterleavedBufferAttribute === true) return void 0;
4656
+ parts.push(
4657
+ `${name}:${attr.itemSize}:${attr.normalized ? 1 : 0}:${attr.array.constructor.name}`
4658
+ );
4659
+ }
4660
+ return parts.join("|");
4661
+ }
4662
+ function mergeSiblingGeometries(geometries) {
4663
+ const first = geometries[0];
4664
+ const merged = first.clone();
4665
+ const names = Object.keys(first.attributes);
4666
+ const totalVertices = geometries.reduce(
4667
+ (sum, geom) => sum + (geom.getAttribute("position")?.count ?? 0),
4668
+ 0
4669
+ );
4670
+ for (const name of names) {
4671
+ const sample = first.getAttribute(name);
4672
+ const itemSize = sample.itemSize;
4673
+ const ArrayCtor = sample.array.constructor;
4674
+ const AttrCtor = sample.constructor;
4675
+ const buffer = new ArrayCtor(totalVertices * itemSize);
4676
+ let offset = 0;
4677
+ for (const geom of geometries) {
4678
+ const attr = geom.getAttribute(name);
4679
+ buffer.set(attr.array, offset * itemSize);
4680
+ offset += attr.count;
4681
+ }
4682
+ merged.setAttribute(name, new AttrCtor(buffer, itemSize, sample.normalized));
4683
+ }
4684
+ if (first.index !== null) {
4685
+ let totalIndices = 0;
4686
+ for (const geom of geometries) totalIndices += geom.index?.count ?? 0;
4687
+ const indexBuffer = new Array(totalIndices);
4688
+ let writeAt = 0;
4689
+ let vertexOffset = 0;
4690
+ for (const geom of geometries) {
4691
+ const idx = geom.index;
4692
+ const arr = idx.array;
4693
+ for (let i = 0; i < idx.count; i += 1) {
4694
+ indexBuffer[writeAt + i] = arr[i] + vertexOffset;
4695
+ }
4696
+ writeAt += idx.count;
4697
+ vertexOffset += geom.getAttribute("position")?.count ?? 0;
4698
+ }
4699
+ merged.setIndex(indexBuffer);
4700
+ }
4701
+ merged.computeBoundingBox();
4702
+ merged.computeBoundingSphere();
4703
+ return merged;
4704
+ }
4705
+ function siblingMergeKey(mesh, materialIds) {
4706
+ if (mesh.isMesh !== true || Array.isArray(mesh.material) || mesh.children.length > 0 || !hasIdentityLocalTransform(mesh) || mesh.morphTargetInfluences !== void 0 && mesh.morphTargetInfluences.length > 0) {
4707
+ return void 0;
4708
+ }
4709
+ const materialId = materialIds.get(mesh.material);
4710
+ if (materialId === void 0) return void 0;
4711
+ const layout = geometryLayoutSignature(mesh.geometry);
4712
+ if (layout === void 0) return void 0;
4713
+ return `${materialId}|${mesh.castShadow ? 1 : 0}|${mesh.receiveShadow ? 1 : 0}|${JSON.stringify(mesh.userData ?? {})}|${layout}`;
4714
+ }
4715
+ function mergeDuplicateCityMeshes(group, materialIds) {
4716
+ const buckets = /* @__PURE__ */ new Map();
4717
+ for (const child of [...group.children]) {
4718
+ const mesh = child;
4719
+ const key = siblingMergeKey(mesh, materialIds);
4720
+ if (key === void 0) continue;
4721
+ let list = buckets.get(key);
4722
+ if (list === void 0) {
4723
+ list = [];
4724
+ buckets.set(key, list);
4725
+ }
4726
+ list.push(mesh);
4727
+ }
4728
+ for (const meshes of buckets.values()) {
4729
+ if (meshes.length < 2) continue;
4730
+ const first = meshes[0];
4731
+ first.geometry = mergeSiblingGeometries(meshes.map((mesh) => mesh.geometry));
4732
+ for (let i = 1; i < meshes.length; i += 1) {
4733
+ group.remove(meshes[i]);
4734
+ }
4735
+ }
4736
+ }
4432
4737
  async function buildCity(options) {
4433
4738
  const errors = [];
4434
4739
  const kit = apex(errors);
@@ -4443,11 +4748,15 @@ async function buildCity(options) {
4443
4748
  const roadChanges = Object.entries(road).filter(
4444
4749
  ([key, value]) => cityRoadDefaults[key] !== value
4445
4750
  );
4751
+ const { settings: bake, changes: bakeChanges } = bakeSettings(options);
4446
4752
  await kit.loadMaps();
4447
4753
  const profile = roadChanges.some(
4448
4754
  ([key]) => ["roadWidth", "roadLength", "bendAngle", "bendRadius", "bendSide"].includes(key)
4449
4755
  );
4450
4756
  const group = kit.build(module, parameters, roadChanges.length > 0 ? road : void 0, profile);
4757
+ applyCityMaterialOptions(group, bake);
4758
+ const materialIds = dedupeCityMaterials(group);
4759
+ mergeDuplicateCityMeshes(group, materialIds);
4451
4760
  const glb = new Uint8Array(
4452
4761
  await new kit.GLTFExporter().parseAsync(group, {
4453
4762
  binary: true,
@@ -4473,7 +4782,7 @@ async function buildCity(options) {
4473
4782
  const changed = Object.entries(parameters).filter(
4474
4783
  ([key, value]) => key !== "seed" && kit.defaults[key] !== value
4475
4784
  );
4476
- changed.push(...roadChanges);
4785
+ changed.push(...roadChanges, ...bakeChanges);
4477
4786
  const tag = changed.length === 0 ? "" : `-f${createHash("sha256").update(JSON.stringify(changed)).digest("hex").slice(0, 8)}`;
4478
4787
  return {
4479
4788
  glb,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threenative/procedural-environment",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "license": "MIT",
5
5
  "description": "Optional, bake-first procedural nature GLBs for ThreeNative: trees and cover (Arbor), forest floor (forest-kit) and rocks, cliffs and mountains (Outcrop), found by biome.",
6
6
  "homepage": "https://github.com/ThreeNativeHQ/threenative#readme",