@scenoco-three/unity 1.2.1 → 1.3.1

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/convert.d.ts CHANGED
@@ -114,6 +114,30 @@ export interface UnityMaterial {
114
114
  /** How often the textures repeat: three's `texture.repeat`, Unity's tiling. */
115
115
  tiling?: number[];
116
116
  }
117
+ /**
118
+ * A terrain as Unity's `TerrainData` wants it. SceNoCo's is centred on its node with heights in
119
+ * metres; Unity's starts at its object's corner with heights 0..1 of `size.y` above it, so the
120
+ * Terrain sits on a child at `offset`. Rows run along Unity's +z, which is three's -z.
121
+ */
122
+ export interface UnityTerrain {
123
+ path: string;
124
+ /** Unity's `size`: width, the height span, length. */
125
+ size: number[];
126
+ /** Where the Terrain's child sits under the node: its corner and its lowest point. */
127
+ offset: number[];
128
+ heightmapResolution: number;
129
+ /** 0..1 of `size.y`, row by row from Unity's z = 0: `heights[y * n + x]`. */
130
+ heights: number[];
131
+ /** A power of two, as Unity needs, resampled from the game's. */
132
+ alphamapResolution: number;
133
+ /** 0..1, `alphamaps[(y * a + x) * layers + layer]`. */
134
+ alphamaps: number[];
135
+ layers: {
136
+ name: string;
137
+ tileSize: number;
138
+ color: string;
139
+ }[];
140
+ }
117
141
  export interface UnityPrefab {
118
142
  path: string;
119
143
  root: UnityNode;
@@ -142,6 +166,7 @@ export interface UnityScene {
142
166
  }
143
167
  export interface UnityExport {
144
168
  meshes: UnityMesh[];
169
+ terrains: UnityTerrain[];
145
170
  materials: UnityMaterial[];
146
171
  /** Ordered so a nested prefab comes before the prefabs that use it. */
147
172
  prefabs: UnityPrefab[];
package/dist/convert.js CHANGED
@@ -44,6 +44,20 @@ export function convert(snap, options = {}) {
44
44
  materialPath.set(id, path);
45
45
  return material(m, path, options.textures, copies, warnings);
46
46
  });
47
+ const terrains = [];
48
+ const terrainPath = new Map();
49
+ const terrainOf = (fields) => {
50
+ const key = JSON.stringify(fields);
51
+ let path = terrainPath.get(key);
52
+ if (!path) {
53
+ path = paths.take('Assets/Terrains', 'Terrain', '.asset');
54
+ terrainPath.set(key, path);
55
+ const t = terrain(fields, path);
56
+ terrains.push(t.terrain);
57
+ warnings.push(...t.warnings);
58
+ }
59
+ return { asset: path };
60
+ };
47
61
  const prefabPath = new Map();
48
62
  const sceneName = new Map();
49
63
  for (const p of snap.prefabs) {
@@ -69,6 +83,8 @@ export function convert(snap, options = {}) {
69
83
  return { asset: materialPath.get(v.material) };
70
84
  if ('geometry' in v)
71
85
  return { asset: meshPath.get(v.geometry) };
86
+ if ('object' in v && v.object.type === 'TerrainData')
87
+ return terrainOf(v.object.fields);
72
88
  if ('object' in v)
73
89
  return { object: { type: v.object.type, fields: Object.fromEntries(Object.entries(v.object.fields).map(([k, f]) => [k, value(f)])) } };
74
90
  return v;
@@ -187,7 +203,7 @@ export function convert(snap, options = {}) {
187
203
  ignore2D: given.ignore2D.map(([a, b]) => [unityLayer(a), unityLayer(b)]),
188
204
  ignore3D: given.ignore3D.map(([a, b]) => [unityLayer(a), unityLayer(b)]),
189
205
  };
190
- return { data: { meshes, materials, prefabs, scenes, layers, warnings }, scripts: scripts(snap, value, options.source), copies };
206
+ return { data: { meshes, terrains, materials, prefabs, scenes, layers, warnings }, scripts: scripts(snap, value, options.source), copies };
191
207
  }
192
208
  /** Every node reference in `roots` one root further along; the scene itself (`''`) is now the first root. */
193
209
  function shiftNodes(roots) {
@@ -224,6 +240,67 @@ class Paths {
224
240
  return path;
225
241
  }
226
242
  }
243
+ const numbers = (v) => v && typeof v === 'object' && 'array' in v ? v.array.map((x) => (typeof x === 'number' ? x : 0)) : [];
244
+ /** A terrain's metres as Unity's TerrainData: mirrored in z, anchored at its corner, heights 0..1 of their span. */
245
+ function terrain(f, path) {
246
+ const warnings = [];
247
+ const width = f.width;
248
+ const depth = f.depth;
249
+ const n = f.heightmapResolution;
250
+ const metres = numbers(f.heights);
251
+ let low = Infinity;
252
+ let high = -Infinity;
253
+ for (const h of metres) {
254
+ low = Math.min(low, h);
255
+ high = Math.max(high, h);
256
+ }
257
+ if (!Number.isFinite(low))
258
+ low = high = 0;
259
+ // Unity's terrain needs some height to span; a flat one gets a metre.
260
+ const span = high - low || 1;
261
+ const heights = new Array(n * n);
262
+ for (let r = 0; r < n; r++) {
263
+ for (let c = 0; c < n; c++)
264
+ heights[(n - 1 - r) * n + c] = Math.round(((metres[r * n + c] - low) / span) * 1e5) / 1e5;
265
+ }
266
+ const layerValues = f.terrainLayers && typeof f.terrainLayers === 'object' && 'array' in f.terrainLayers ? f.terrainLayers.array : [];
267
+ const layers = layerValues.map((l) => {
268
+ const fields = l && typeof l === 'object' && 'object' in l ? l.object.fields : {};
269
+ const color = fields.color && typeof fields.color === 'object' && 'color' in fields.color ? fields.color.color : '#808080';
270
+ if (fields.textured)
271
+ warnings.push(`${path}: layer "${fields.name || 'unnamed'}" has a texture, which is not exported — it is its colour in Unity.`);
272
+ return { name: String(fields.name ?? ''), tileSize: Number(fields.tileSize ?? 10), color };
273
+ });
274
+ const a = f.alphamapResolution;
275
+ const bytes = numbers(f.alphamaps);
276
+ const unityA = Math.min(Math.max(2 ** Math.ceil(Math.log2(Math.max(a, 1))), 16), 2048);
277
+ const alphamaps = [];
278
+ if (layers.length > 0) {
279
+ for (let y = 0; y < unityA; y++) {
280
+ const r = Math.min(a - 1, Math.floor((1 - (y + 0.5) / unityA) * a));
281
+ for (let x = 0; x < unityA; x++) {
282
+ const c = Math.min(a - 1, Math.floor(((x + 0.5) / unityA) * a));
283
+ for (let l = 0; l < layers.length; l++) {
284
+ const byte = bytes.length ? bytes[l * a * a + r * a + c] : l === 0 ? 255 : 0;
285
+ alphamaps.push(Math.round((byte / 255) * 1000) / 1000);
286
+ }
287
+ }
288
+ }
289
+ }
290
+ return {
291
+ terrain: {
292
+ path,
293
+ size: [width, span, depth],
294
+ offset: [-width / 2, low, -depth / 2],
295
+ heightmapResolution: n,
296
+ heights,
297
+ alphamapResolution: unityA,
298
+ alphamaps,
299
+ layers,
300
+ },
301
+ warnings,
302
+ };
303
+ }
227
304
  function mesh(g, path) {
228
305
  const vertices = g.position.map((v, i) => (i % 3 === 2 && v !== 0 ? -v : v));
229
306
  const out = { path, vertices, submeshes: [] };
package/dist/page.js CHANGED
@@ -289,7 +289,9 @@ export async function convertPage(root, documents, options = {}) {
289
289
  // A rule for the page around the game — html, body, the canvas, the loading screen — has no element here.
290
290
  // Classes are kept whether or not the page as written has them: code puts them on as the game runs.
291
291
  const ids = new Set([...inside].map((e) => e.attrs.id).filter(Boolean));
292
- const kept = rule.selectors.filter((sel) => [...sel.matchAll(/#([\w-]+)/g)].every((m) => ids.has(m[1])) && !/(^|[\s>])(html|body|canvas|head)\b/.test(sel));
292
+ const kept = rule.selectors.filter(
293
+ // `:where(…)` is the page standing in for USS's own defaults: Unity has them, and USS has no `:where`.
294
+ (sel) => [...sel.matchAll(/#([\w-]+)/g)].every((m) => ids.has(m[1])) && !/(^|[\s>])(html|body|canvas|head)\b/.test(sel) && !sel.includes(':where('));
293
295
  if (kept.length === 0)
294
296
  continue;
295
297
  const declarations = respell(rule);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scenoco-three/unity",
3
- "version": "1.2.1",
3
+ "version": "1.3.1",
4
4
  "description": "Export a SceNoCo game's prefabs, scenes, meshes and materials into a Unity project: nested prefabs, shared materials, behaviours as MonoBehaviours with their fields wired.",
5
5
  "keywords": [
6
6
  "three",
@@ -54,7 +54,7 @@
54
54
  "rolldown": "^1.0.3"
55
55
  },
56
56
  "peerDependencies": {
57
- "@scenoco-three/core": "^1.2.0",
57
+ "@scenoco-three/core": "^1.3.1",
58
58
  "vite": ">=6"
59
59
  }
60
60
  }
package/unity/PORTING.md CHANGED
@@ -68,6 +68,13 @@ is the rules for that. It is rewritten by every export.
68
68
  saving anything.
69
69
  - **Particle systems** came across as Unity's own, module by module: `play()`, `stop()` and
70
70
  `isPlaying` are the same.
71
+ - **Terrains** came across as Unity's `TerrainData` assets, with the `Terrain` and `TerrainCollider`
72
+ on a child named Terrain at the data's corner: SceNoCo's terrain is centred on its node with heights
73
+ in metres, Unity's starts at its object with heights 0..1 of `size.y`. A layer is its colour; a
74
+ layer's texture is set in Unity. In code, `terrain.sampleHeight(p)` is `Terrain.SampleHeight(p)`;
75
+ `data.heightAt(x, z)` (metres from the centre) is `terrain.SampleHeight` at that point under the
76
+ node, and `steepnessAt` is `terrainData.GetSteepness` at its 0..1 position. The game's own height
77
+ function, if it has one, ports as it is.
71
78
 
72
79
  ## Input
73
80
 
@@ -61,6 +61,8 @@ namespace SceNoCo
61
61
  if (data.TryGetValue("input", out var input)) Try(() => Project.Input((string)input), "input actions");
62
62
 
63
63
  foreach (var m in List(data["meshes"])) Try(() => MakeMesh(Obj(m)), Str(Obj(m), "path"));
64
+ Terrains.Offsets.Clear();
65
+ if (data.TryGetValue("terrains", out var ts)) foreach (var t in List(ts)) Try(() => Terrains.Make(Obj(t)), Str(Obj(t), "path"));
64
66
  foreach (var m in List(data["materials"])) Try(() => MakeMaterial(Obj(m)), Str(Obj(m), "path"));
65
67
  AssetDatabase.SaveAssets();
66
68
 
@@ -384,6 +386,7 @@ namespace SceNoCo
384
386
  else if (type == "ParticleSystem") Particles.Add(go, Obj(comp["fields"]), w => warnings.Add($"{Where(comp, n)}: {w}"));
385
387
  else if (type == "UIDocument") MakeDocument(go, Obj(comp["fields"]), Where(comp, n));
386
388
  else if (Volumes.Add(go, type, Obj(comp["fields"]))) { }
389
+ else if (Terrains.Add(go, type, Obj(comp["fields"]), w => warnings.Add($"{Where(comp, n)}: {w}"))) { }
387
390
  else if (!Physics.Add(go, type, Obj(comp["fields"]))) warnings.Add($"{Where(comp, n)}: {type} has no Unity counterpart here — left off.");
388
391
  }
389
392
 
@@ -917,6 +920,98 @@ namespace SceNoCo
917
920
  d.TryGetValue(key, out var v) && v is Dictionary<string, object> o && o.TryGetValue("color", out var hex) ? Hex((string)hex) : fallback;
918
921
  }
919
922
 
923
+ /// <summary>
924
+ /// A game's terrain as Unity's own: a TerrainData asset holding its heights (0..1 of size.y, as the
925
+ /// exporter wrote them) and a layer per colour, and the Terrain and TerrainCollider on a child at the
926
+ /// data's corner — Unity's terrain starts at its object, SceNoCo's is centred on its node.
927
+ /// </summary>
928
+ static class Terrains
929
+ {
930
+ public static readonly Dictionary<string, Vector3> Offsets = new Dictionary<string, Vector3>();
931
+
932
+ public static void Make(Dictionary<string, object> t)
933
+ {
934
+ var path = Str(t, "path");
935
+ var data = AssetDatabase.LoadAssetAtPath<TerrainData>(path);
936
+ var created = data == null;
937
+ if (created) data = new TerrainData();
938
+ var n = (int)Num(t, "heightmapResolution", 33);
939
+ data.heightmapResolution = n;
940
+ data.size = V3(t["size"]);
941
+ var flat = Floats(t["heights"]);
942
+ var heights = new float[n, n];
943
+ for (var y = 0; y < n; y++) for (var x = 0; x < n; x++) heights[y, x] = flat[y * n + x];
944
+ data.SetHeights(0, 0, heights);
945
+ if (created) SaveAsset(data, path);
946
+ // The layers live inside the data's asset, each with a one-pixel texture of its colour.
947
+ foreach (var old in AssetDatabase.LoadAllAssetRepresentationsAtPath(path)) Object.DestroyImmediate(old, true);
948
+ var specs = List(t["layers"]).Select(Obj).ToList();
949
+ var layers = specs.Select(spec =>
950
+ {
951
+ var texture = new Texture2D(1, 1) { name = Str(spec, "name") + " colour" };
952
+ texture.SetPixel(0, 0, Hex(Str(spec, "color")));
953
+ texture.Apply();
954
+ AssetDatabase.AddObjectToAsset(texture, data);
955
+ var tile = Num(spec, "tileSize", 10);
956
+ var layer = new TerrainLayer { name = Str(spec, "name"), diffuseTexture = texture, tileSize = new Vector2(tile, tile) };
957
+ AssetDatabase.AddObjectToAsset(layer, data);
958
+ return layer;
959
+ }).ToArray();
960
+ data.terrainLayers = layers;
961
+ if (layers.Length > 0)
962
+ {
963
+ var a = (int)Num(t, "alphamapResolution", 16);
964
+ data.alphamapResolution = a;
965
+ var w = Floats(t["alphamaps"]);
966
+ var maps = new float[a, a, layers.Length];
967
+ for (var y = 0; y < a; y++) for (var x = 0; x < a; x++) for (var l = 0; l < layers.Length; l++) maps[y, x, l] = w[(y * a + x) * layers.Length + l];
968
+ data.SetAlphamaps(0, 0, maps);
969
+ }
970
+ EditorUtility.SetDirty(data);
971
+ Offsets[path] = V3(t["offset"]);
972
+ }
973
+
974
+ public static bool Add(GameObject go, string type, Dictionary<string, object> f, Action<string> warn)
975
+ {
976
+ if (type != "Terrain" && type != "TerrainCollider") return false;
977
+ var path = f.TryGetValue("terrainData", out var v) && v is Dictionary<string, object> d && d.TryGetValue("asset", out var p) ? (string)p : null;
978
+ var data = path != null ? AssetDatabase.LoadAssetAtPath<TerrainData>(path) : null;
979
+ if (data == null)
980
+ {
981
+ warn($"{type} has no exported terrainData — left off.");
982
+ return true;
983
+ }
984
+ var child = go.transform.Find("Terrain")?.gameObject;
985
+ if (child == null)
986
+ {
987
+ child = new GameObject("Terrain");
988
+ child.transform.SetParent(go.transform, false);
989
+ child.transform.localPosition = Offsets.TryGetValue(path, out var at) ? at : Vector3.zero;
990
+ if ((go.transform.lossyScale - Vector3.one).sqrMagnitude > 1e-6f) warn("a Unity terrain ignores its object's scale — size the TerrainData instead.");
991
+ }
992
+ if (type == "Terrain")
993
+ {
994
+ var terrain = child.AddComponent<Terrain>();
995
+ terrain.terrainData = data;
996
+ terrain.heightmapPixelError = Num(f, "heightmapPixelError", 5);
997
+ terrain.shadowCastingMode = Bool(f, "castShadows", true) ? ShadowCastingMode.On : ShadowCastingMode.Off;
998
+ var lit = Shader.Find("Universal Render Pipeline/Terrain/Lit");
999
+ if (lit != null) terrain.materialTemplate = TerrainMaterial(lit);
1000
+ }
1001
+ else child.AddComponent<TerrainCollider>().terrainData = data;
1002
+ return true;
1003
+ }
1004
+
1005
+ /** URP's terrain material, one for the project: a terrain with none draws pink there. */
1006
+ static Material TerrainMaterial(Shader lit)
1007
+ {
1008
+ const string path = "Assets/Terrains/TerrainLit.mat";
1009
+ var mat = AssetDatabase.LoadAssetAtPath<Material>(path);
1010
+ if (mat == null) SaveAsset(mat = new Material(lit), path);
1011
+ return mat;
1012
+ }
1013
+ }
1014
+
920
1015
  static class Physics
921
1016
  {
922
1017
  public static bool Add(GameObject go, string type, Dictionary<string, object> f)