Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

3.6 KB
Raw Blame
/** Shared CLI/MCP JSON authoring boundary. Library pins never imply project membership. */
import {
  MATERIAL_LIBRARY_LIMITS,
  assertMaterialJson,
  proceduralMaterialDraftSchema,
  proceduralMaterialDraftV2Schema,
  type MaterialLibrary,
  type MaterialManifest,
  type MaterialRecord,
} from './material-library';
import {
  createMaterialRecordV1,
  createMaterialRecordV2,
  resolveMaterialRecordClosure,
} from './material-library-node';
import { canonicalizeTextureAtlasSpecV1 } from './texture-atlas-contract';
import type { MaterialMapPinV1 } from './pinned-material-map';

/**
 * A save names a parent the library holds; import does not, as asset import does not. The record
 * builders cannot check this because they have no library.
 */
async function assertMaterialParent(
  draft: { materialId: string; parentRevision?: string | undefined },
  library: MaterialLibrary,
): Promise<void> {
  if (!draft.parentRevision) return;
  try {
    if (library.readManifest) await library.readManifest(draft.materialId, draft.parentRevision);
    else await library.read(draft.materialId, draft.parentRevision);
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
    throw new Error(
      `parentRevision ${draft.parentRevision} is not a saved revision of material ${draft.materialId}. A parent must be an existing revision of the same materialId; list materials to see their revision IDs.`,
    );
  }
}

export async function createProceduralMaterialRecord(
  value: unknown,
  library: MaterialLibrary,
): Promise<{ record: MaterialRecord; dependencies: MaterialRecord[] }> {
  assertMaterialJson(value);
  if (
    new TextEncoder().encode(JSON.stringify(value)).length >
    MATERIAL_LIBRARY_LIMITS.maxManifestBytes
  )
    throw new Error('Material draft exceeds size limit');
  if (!value || typeof value !== 'object' || Array.isArray(value))
    throw new Error('Material draft must be a JSON object');
  if (!Object.hasOwn(value, 'schemaVersion')) {
    const draft = proceduralMaterialDraftSchema.parse(value);
    await assertMaterialParent(draft, library);
    return { record: await createMaterialRecordV1(draft), dependencies: [] };
  }

  const draft = proceduralMaterialDraftV2Schema.parse(value);
  await assertMaterialParent(draft, library);
  const pins = new Map<string, MaterialMapPinV1>();
  for (const map of draft.maps) {
    if (!map.atlas) continue;
    for (const region of canonicalizeTextureAtlasSpecV1(map.atlas).regions) {
      if (region.source.kind !== 'resource') continue;
      const pin = region.source.pin;
      pins.set(`${pin.resourceId}@${pin.revisionId}`, pin);
    }
  }
  if (pins.size > MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)
    throw new Error('Material source closure count limit exceeded');
  const roots: MaterialManifest[] = [];
  if (pins.size && !library.readManifest)
    throw new Error('Pinned atlas creation requires a material library with readManifest support.');
  for (const pin of pins.values()) {
    const manifest = await library.readManifest!(pin.resourceId, pin.revisionId);
    if (manifest.materialId !== pin.resourceId || manifest.revisionId !== pin.revisionId)
      throw new Error('Material source pin identity mismatch');
    roots.push(manifest);
  }
  const dependencies = roots.length
    ? await resolveMaterialRecordClosure(roots, {
        readManifest: (id, revision) => library.readManifest!(id, revision),
        read: (id, revision) =>
          library.readRecordFiles
            ? library.readRecordFiles(id, revision)
            : library.read(id, revision),
      })
    : [];
  return { record: await createMaterialRecordV2(draft, { materials: dependencies }), dependencies };
}