@xprite/lighter 0.1.0 → 0.1.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"normal-map-lighting.d.ts","sourceRoot":"","sources":["../src/normal-map-lighting.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,KAAK,WAAW,EAAE,KAAK,KAAK,EAAE,KAAK,IAAI,EAAE,MAAM,WAAW,CAAC;AAGlG,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,KAAK,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,IAAI,CAAC;IACZ,OAAO,EAAE,OAAO,CAAC;IACjB;;;;OAIG;IACH,OAAO,CAAC,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC;CAChD;AAgBD,eAAO,MAAM,mBAAmB;;;;;EAK9B,CAAC;AAEH,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,qBAAqB,CAUjG;AAsBD,MAAM,WAAW,yBAAyB;IACxC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;IAC9B,QAAQ,CAAC,UAAU,EAAE,YAAY,CAAC;IAClC,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;IAC3B,QAAQ,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAAC;CACpC;AAGD,gFAAgF;AAChF,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,WAAW,GAAG,IAAI,EAC3B,SAAS,GAAE,WAAW,GAAG,IAAW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E,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;IAC9B,QAAQ,CAAC,UAAU,EAAE,YAAY,CAAC;IAClC,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;IAC3B,QAAQ,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAAC;CACpC;AAGD,gFAAgF;AAChF,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,WAAW,GAAG,IAAI,EAC3B,SAAS,GAAE,WAAW,GAAG,IAAW,GACnC,yBAAyB,CAoC3B;AAgCD,mFAAmF;AACnF,wBAAgB,+BAA+B,CAC7C,MAAM,EAAE,yBAAyB,EACjC,OAAO,EAAE,qBAAqB,GAC7B,WAAW,CAyCb;AAED,0FAA0F;AAC1F,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,yBAAyB,EACjC,OAAO,EAAE,WAAW,CAAC,qBAAqB,CAAC,SAAS,CAAC,CAAC,EACtD,OAAO,UAAQ,GACd,WAAW,CAab;AAED,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,WAAW,GAAG,IAAI,EAC3B,OAAO,EAAE,qBAAqB,EAC9B,SAAS,GAAE,WAAW,GAAG,IAAW,GACnC,WAAW,CAKb"}
@@ -6,7 +6,8 @@ const DEFAULT_AMBIENT = 15;
6
6
  const PERCENT = 100;
7
7
  const DEFAULT_MASK_STRENGTH = PERCENT;
8
8
  const MIN_DISTANCE = 0.000001;
9
- const LIGHT_RADIUS_FACTOR = 0.75;
9
+ // A fixed reference distance in source pixels keeps the light independent of canvas padding.
10
+ const LIGHT_FALLOFF_DISTANCE_SQUARED = 32 ** 2;
10
11
  const DELIGHT_ELEVATION = 45;
11
12
  const DELIGHT_AMBIENT = 0.15;
12
13
  const SRGB_DECODE_LIMIT = 0.04045;
@@ -110,7 +111,6 @@ export function renderPreparedNormalMapLighting(source, options) {
110
111
  const ambient = limit(options.ambient, NORMAL_LIGHT_LIMITS.ambient, DEFAULT_AMBIENT) / PERCENT;
111
112
  const maskStrength = limit(options.maskStrength, NORMAL_LIGHT_LIMITS.maskStrength, DEFAULT_MASK_STRENGTH) / PERCENT;
112
113
  const light = options.color.map(linear);
113
- const radius = Math.max(1, Math.max(source.width, source.height) * LIGHT_RADIUS_FACTOR);
114
114
  const x = Number.isFinite(options.position.x) ? options.position.x : source.width / 2;
115
115
  const y = Number.isFinite(options.position.y) ? options.position.y : source.height / 2;
116
116
  const ySign = options.invertY ? -1 : 1;
@@ -129,7 +129,7 @@ export function renderPreparedNormalMapLighting(source, options) {
129
129
  source.directions[vector + 2] * height) /
130
130
  Math.sqrt(distanceSquared));
131
131
  const reception = source.mask ? 1 - maskStrength * (1 - source.mask[i]) : 1;
132
- const direct = (power * diffuse * reception) / (1 + distanceSquared / (radius * radius));
132
+ const direct = (power * diffuse * reception) / (1 + distanceSquared / LIGHT_FALLOFF_DISTANCE_SQUARED);
133
133
  const gain = delight ? delight(vector) : 1;
134
134
  for (let channel = 0; channel < 3; channel++)
135
135
  data[at + channel] = encoded(source.colors[vector + channel] * gain * (ambient + direct * light[channel]));
@@ -4,6 +4,8 @@
4
4
  * https://www.moonfell-rpg.com/Pixel-Art-Lighter-v3.5.22.html
5
5
  */
6
6
  import { type PixelBuffer } from "./base.js";
7
+ import { segmentLightingMapSource } from "./lighting-map-source.js";
8
+ import { type PaintedLightEstimate } from "./normal-map-light-estimate.js";
7
9
  export declare enum NormalMapPreset {
8
10
  Architecture = "architecture",
9
11
  Character = "character",
@@ -31,11 +33,32 @@ export declare const NORMAL_MAP_LIMITS: Readonly<{
31
33
  }>;
32
34
  export declare function defaultNormalMapOptions(preset?: NormalMapPreset): NormalMapOptions;
33
35
  export declare function normalizeNormalMapOptions(input: Partial<NormalMapOptions>): NormalMapOptions;
36
+ export interface GenerateGeometryOptions extends Partial<NormalMapOptions> {
37
+ /**
38
+ * When true, also include the pre-quantization continuous unit Float32 normals
39
+ * (`continuousDirections`) before per-cluster averaging and 8-azimuth facet quantization.
40
+ * Does not modify `normalMap` or `directions`. Default false.
41
+ */
42
+ readonly includeContinuousDirections?: boolean;
43
+ }
44
+ export interface NormalMapGeometry {
45
+ readonly normalMap: PixelBuffer;
46
+ readonly directions: Float32Array;
47
+ /** Pre-quantization continuous unit Float32 normals (present only when `includeContinuousDirections: true`). */
48
+ readonly continuousDirections?: Float32Array;
49
+ readonly heightField: Float32Array;
50
+ readonly silhouetteDistance: Float32Array;
51
+ readonly thinOutline: Uint8Array;
52
+ readonly lightSignal: Float32Array;
53
+ readonly paintedLight: PaintedLightEstimate | null;
54
+ readonly segmented: ReturnType<typeof segmentLightingMapSource>;
55
+ }
34
56
  /** Cache source segmentation, silhouette distance and geometry between parameter edits. */
35
57
  export declare function createNormalMapGenerator(albedo: PixelBuffer, shading?: PixelBuffer): {
36
58
  setShading(source: PixelBuffer | null): void;
37
59
  suggestPaintedLightAngle(): number | null;
38
60
  generate(input?: Partial<NormalMapOptions>): PixelBuffer;
61
+ generateGeometry(input?: GenerateGeometryOptions): NormalMapGeometry;
39
62
  };
40
63
  export declare function generateNormalMap(albedo: PixelBuffer, input?: Partial<NormalMapOptions>): PixelBuffer;
41
64
  //# sourceMappingURL=normal-map.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"normal-map.d.ts","sourceRoot":"","sources":["../src/normal-map.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAqB,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAUhE,oBAAY,eAAe;IACzB,YAAY,iBAAiB;IAC7B,SAAS,cAAc;IACvB,MAAM,WAAW;IACjB,OAAO,YAAY;CACpB;AACD,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,eAAe,CAAC;IACxB,aAAa,EAAE,MAAM,CAAC;IACtB,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,OAAO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,OAAO,CAAC,gBAAgB,CAAC,GAAG,WAAW,CAAC;IACzD,gBAAgB,CAAC,KAAK,CAAC,EAAE,uBAAuB,GAAG,iBAAiB,CAAC;CACtE,CAwYA;AAED,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,WAAW,EACnB,KAAK,GAAE,OAAO,CAAC,gBAAgB,CAAM,GACpC,WAAW,CAEb"}
@@ -47,6 +47,8 @@ const TILT_LEVEL_HIGH = 0.72;
47
47
  const TILT_LEVEL_MAX = 0.9;
48
48
  const ARCHITECTURE_TILT = 0.6;
49
49
  const ARCHITECTURE_FLAT_LIMIT = 0.06;
50
+ const ARCHITECTURE_EDGE_TILT = 0.35;
51
+ const ARCHITECTURE_EDGE_MIN_LENGTH = 12;
50
52
  const FACET_AREA_BASE = 180;
51
53
  const FACET_AREA_SCALE = 1.1;
52
54
  const FACET_REFERENCE_SIDE = 64;
@@ -94,7 +96,10 @@ export function normalizeNormalMapOptions(input) {
94
96
  for (const key of Object.keys(NORMAL_MAP_LIMITS)) {
95
97
  const value = input[key];
96
98
  if (typeof value === "number" && Number.isFinite(value))
97
- result[key] = Math.round(Math.max(0, Math.min(NORMAL_MAP_LIMITS[key], value)));
99
+ result[key] =
100
+ key === "paintedLightAngle"
101
+ ? ((Math.round(value) % 360) + 360) % 360
102
+ : Math.round(Math.max(0, Math.min(NORMAL_MAP_LIMITS[key], value)));
98
103
  }
99
104
  for (const key of ["mergeOutlines", "invertY"])
100
105
  if (typeof input[key] === "boolean")
@@ -103,7 +108,8 @@ export function normalizeNormalMapOptions(input) {
103
108
  }
104
109
  /** Cache source segmentation, silhouette distance and geometry between parameter edits. */
105
110
  export function createNormalMapGenerator(albedo, shading) {
106
- const { w, h, N, a, fg, lum, labels, lo, hi, adjacent, queue, clusters, foregroundArea } = segmentLightingMapSource(albedo, LightingMapRegionMode.Perceptual);
111
+ const segmented = segmentLightingMapSource(albedo, LightingMapRegionMode.Perceptual);
112
+ const { w, h, N, a, fg, lum, labels, lo, hi, adjacent, queue, clusters, foregroundArea } = segmented;
107
113
  const spriteScale = Math.min(FACET_MAX_SPRITE_SCALE, Math.sqrt(foregroundArea) / FACET_REFERENCE_SIDE);
108
114
  const distance = new Float32Array(N);
109
115
  distance.fill(N);
@@ -139,6 +145,7 @@ export function createNormalMapGenerator(albedo, shading) {
139
145
  let cachedField = null;
140
146
  let cachedKey = "";
141
147
  let cachedDirections = null;
148
+ let cachedContinuousDirections = null;
142
149
  let shadingSource;
143
150
  let lightSignal;
144
151
  let paintedEstimate;
@@ -157,144 +164,148 @@ export function createNormalMapGenerator(albedo, shading) {
157
164
  lightSignal = undefined;
158
165
  paintedEstimate = undefined;
159
166
  cachedKey = "";
167
+ cachedContinuousDirections = null;
160
168
  };
161
169
  if (shading)
162
170
  setShading(shading);
163
- return {
164
- setShading,
165
- suggestPaintedLightAngle() {
166
- return estimatePainted()?.angle ?? null;
167
- },
168
- generate(input = {}) {
169
- const options = normalizeNormalMapOptions(input);
170
- const experimental = input.experimental ?? {};
171
- let influence = options.paintedLightInfluence / PERCENT;
172
- let angleDeg = options.paintedLightAngle;
173
- if (influence > 0 && input.paintedLightAngle === undefined) {
174
- const estimate = estimatePainted();
175
- if (estimate) {
176
- angleDeg = estimate.angle;
177
- influence *= Math.min(1, Math.max(0, (estimate.fit - ESTIMATE_FADE_LOW) / (ESTIMATE_FADE_HIGH - ESTIMATE_FADE_LOW)));
178
- }
179
- else
180
- influence = 0;
171
+ const generateInternal = (input = {}, includeContinuous = false) => {
172
+ const options = normalizeNormalMapOptions(input);
173
+ const experimental = input.experimental ?? {};
174
+ let influence = options.paintedLightInfluence / PERCENT;
175
+ let angleDeg = options.paintedLightAngle;
176
+ if (influence > 0 && input.paintedLightAngle === undefined) {
177
+ const estimate = estimatePainted();
178
+ if (estimate) {
179
+ angleDeg = estimate.angle;
180
+ influence *= Math.min(1, Math.max(0, (estimate.fit - ESTIMATE_FADE_LOW) / (ESTIMATE_FADE_HIGH - ESTIMATE_FADE_LOW)));
181
181
  }
182
- const key = JSON.stringify([
183
- options.preset,
184
- options.shapeStrength,
185
- options.smoothing,
186
- options.facets,
187
- options.mergeOutlines,
188
- influence,
189
- influence ? angleDeg : 0,
190
- ]);
191
- let directions = cachedDirections;
192
- if (!directions || cachedKey !== key) {
193
- const preset = options.preset;
194
- const profile = HEIGHT_PROFILES[preset];
195
- const scale = options.shapeStrength / PERCENT;
196
- const fieldKey = JSON.stringify([preset, options.smoothing, influence, experimental]);
197
- let field = cachedField;
198
- if (!field || cachedFieldKey !== fieldKey) {
199
- const distField = experimental.chamferDistance
200
- ? chamferDistance(fg, w, h)
201
- : distance;
202
- const groove = experimental.edgeGroove ?? 0;
203
- const edgeDist = groove > 0 ? colorEdgeDistance(a, fg, w, h) : null;
204
- // silhouette ramp exponent scales from the small-sprite sqrt profile to a
205
- // linear ramp once the sprite is large enough for facets to stay accurate
206
- const pow = experimental.bevelPow ??
207
- Math.min(BEVEL_POW_LINEAR, Math.max(BEVEL_POW_SQRT, BEVEL_POW_SQRT + (spriteScale - BEVEL_POW_PIVOT) * 0.5));
208
- const mid = experimental.midLum ? (lo + hi) / 2 : null;
209
- const lumTerm = experimental.oklab ? new Float32Array(N) : null;
210
- if (lumTerm)
211
- for (let i = 0; i < N; i++)
212
- lumTerm[i] = fg[i]
213
- ? oklabLightness(a[i * 4], a[i * 4 + 1], a[i * 4 + 2])
214
- : 0;
215
- let nextField = new Float32Array(N);
182
+ else
183
+ influence = 0;
184
+ }
185
+ const key = JSON.stringify([
186
+ options.preset,
187
+ options.shapeStrength,
188
+ options.smoothing,
189
+ options.facets,
190
+ options.mergeOutlines,
191
+ influence,
192
+ influence ? angleDeg : 0,
193
+ experimental,
194
+ ]);
195
+ let directions = cachedDirections;
196
+ const needsDirections = !directions || cachedKey !== key;
197
+ const needsContinuousOnly = !needsDirections && includeContinuous && !cachedContinuousDirections;
198
+ if (needsDirections || needsContinuousOnly) {
199
+ const preset = options.preset;
200
+ const profile = HEIGHT_PROFILES[preset];
201
+ const scale = options.shapeStrength / PERCENT;
202
+ const fieldKey = JSON.stringify([preset, options.smoothing, influence, experimental]);
203
+ let field = cachedField;
204
+ if (!field || cachedFieldKey !== fieldKey) {
205
+ const distField = experimental.chamferDistance
206
+ ? chamferDistance(fg, w, h)
207
+ : distance;
208
+ const groove = experimental.edgeGroove ?? 0;
209
+ const edgeDist = groove > 0 ? colorEdgeDistance(a, fg, w, h) : null;
210
+ // silhouette ramp exponent scales from the small-sprite sqrt profile to a
211
+ // linear ramp once the sprite is large enough for facets to stay accurate
212
+ const pow = experimental.bevelPow ??
213
+ Math.min(BEVEL_POW_LINEAR, Math.max(BEVEL_POW_SQRT, BEVEL_POW_SQRT + (spriteScale - BEVEL_POW_PIVOT) * 0.5));
214
+ const mid = experimental.midLum ? (lo + hi) / 2 : null;
215
+ const lumTerm = experimental.oklab ? new Float32Array(N) : null;
216
+ if (lumTerm)
216
217
  for (let i = 0; i < N; i++)
217
- if (fg[i]) {
218
- const convex = Math.pow(Math.min(distField[i], profile.cap) / profile.cap, pow) *
219
- profile.silhouette * Math.sqrt(profile.cap);
220
- const lumPart = lumTerm
221
- ? lumTerm[i] * profile.luminance * (1 - influence)
222
- : mid !== null
223
- ? (lum[i] - mid) * profile.luminance * (1 - influence)
224
- : normalized(i) * profile.luminance * (1 - influence);
225
- const dip = edgeDist ? groove * Math.min(1, edgeDist[i] / 2) : 0;
226
- nextField[i] = convex + lumPart + dip;
227
- }
228
- for (let pass = 0; pass < options.smoothing; pass++) {
229
- let blurred;
230
- if (experimental.maskedBlur) {
231
- blurred = separableMaskedBlur(nextField, fg, w, h);
232
- }
233
- else {
234
- blurred = new Float32Array(N);
235
- for (let i = 0; i < N; i++)
236
- if (fg[i]) {
237
- let sum = nextField[i] * CENTER_SMOOTHING_WEIGHT, count = CENTER_SMOOTHING_WEIGHT;
238
- for (const n of adjacent(i))
239
- if (fg[n]) {
240
- sum += nextField[n];
241
- count++;
242
- }
243
- blurred[i] = sum / count;
244
- }
245
- }
246
- nextField = blurred;
218
+ lumTerm[i] = fg[i]
219
+ ? oklabLightness(a[i * 4], a[i * 4 + 1], a[i * 4 + 2])
220
+ : 0;
221
+ let nextField = new Float32Array(N);
222
+ for (let i = 0; i < N; i++)
223
+ if (fg[i]) {
224
+ const convex = Math.pow(Math.min(distField[i], profile.cap) / profile.cap, pow) *
225
+ profile.silhouette * Math.sqrt(profile.cap);
226
+ const lumPart = lumTerm
227
+ ? lumTerm[i] * profile.luminance * (1 - influence)
228
+ : mid !== null
229
+ ? (lum[i] - mid) * profile.luminance * (1 - influence)
230
+ : normalized(i) * profile.luminance * (1 - influence);
231
+ const dip = edgeDist ? groove * Math.min(1, edgeDist[i] / 2) : 0;
232
+ nextField[i] = convex + lumPart + dip;
247
233
  }
248
- cachedFieldKey = fieldKey;
249
- field = cachedField = nextField;
234
+ for (let pass = 0; pass < options.smoothing; pass++) {
235
+ let blurred;
236
+ if (experimental.maskedBlur) {
237
+ blurred = separableMaskedBlur(nextField, fg, w, h);
238
+ }
239
+ else {
240
+ blurred = new Float32Array(N);
241
+ for (let i = 0; i < N; i++)
242
+ if (fg[i]) {
243
+ let sum = nextField[i] * CENTER_SMOOTHING_WEIGHT, count = CENTER_SMOOTHING_WEIGHT;
244
+ for (const n of adjacent(i))
245
+ if (fg[n]) {
246
+ sum += nextField[n];
247
+ count++;
248
+ }
249
+ blurred[i] = sum / count;
250
+ }
251
+ }
252
+ nextField = blurred;
250
253
  }
251
- const dirs = new Float32Array(N * 3);
252
- const unit = (v) => {
253
- const len = Math.hypot(...v) || 1;
254
- return v.map((n) => n / len);
255
- };
256
- const quantize = (v) => {
257
- v = unit(v);
258
- const tilt = Math.hypot(v[0], v[1]);
259
- if (tilt < FRONT_FACING_LIMIT)
260
- return [0, 0, 1];
261
- const angle = Math.round(Math.atan2(v[1], v[0]) / AZIMUTH_STEP) * AZIMUTH_STEP;
262
- const elevation = preset === NormalMapPreset.Architecture
263
- ? Math.min(TILT_LEVEL_MAX, ARCHITECTURE_TILT * scale)
264
- : tilt < TILT_LOW
265
- ? TILT_LEVEL_LOW
266
- : tilt < TILT_MEDIUM
267
- ? TILT_LEVEL_MEDIUM
268
- : tilt < TILT_HIGH
269
- ? TILT_LEVEL_HIGH
270
- : TILT_LEVEL_MAX;
271
- return [
272
- Math.cos(angle) * elevation,
273
- Math.sin(angle) * elevation,
274
- Math.sqrt(1 - elevation * elevation),
275
- ];
276
- };
277
- const heightField = field;
278
- if (influence)
279
- lightSignal ??= paintedLightSignal(w, h, fg, foregroundArea, lum, shadingSource);
280
- const angle = angleDeg * RADIANS_PER_DEGREE;
281
- const lightX = Math.cos(angle) * influence * PAINTED_LIGHT_TILT_GAIN;
282
- const lightY = Math.sin(angle) * influence * PAINTED_LIGHT_TILT_GAIN;
283
- const normalAt = (pixel) => {
284
- const x = pixel % w;
285
- const y = (pixel / w) | 0;
286
- const center = heightField[pixel];
287
- const at = (neighbor) => (fg[neighbor] ? heightField[neighbor] : center);
288
- const dx = (x < w - 1 ? at(pixel + 1) : center) - (x ? at(pixel - 1) : center);
289
- const dy = (y < h - 1 ? at(pixel + w) : center) - (y ? at(pixel - w) : center);
290
- if (!influence)
291
- return unit([-dx * scale, dy * scale, 1]);
292
- const tilt = lightSignal[pixel];
293
- return unit([-dx * scale + lightX * tilt, dy * scale + lightY * tilt, 1]);
294
- };
295
- for (let i = 0; i < N; i++)
296
- if (fg[i])
297
- dirs.set(normalAt(i), i * 3);
254
+ cachedFieldKey = fieldKey;
255
+ field = cachedField = nextField;
256
+ }
257
+ const dirs = new Float32Array(N * 3);
258
+ const unit = (v) => {
259
+ const len = Math.hypot(...v) || 1;
260
+ return v.map((n) => n / len);
261
+ };
262
+ const quantize = (v) => {
263
+ v = unit(v);
264
+ const tilt = Math.hypot(v[0], v[1]);
265
+ if (tilt < FRONT_FACING_LIMIT)
266
+ return [0, 0, 1];
267
+ const angle = Math.round(Math.atan2(v[1], v[0]) / AZIMUTH_STEP) * AZIMUTH_STEP;
268
+ const elevation = preset === NormalMapPreset.Architecture
269
+ ? Math.min(TILT_LEVEL_MAX, ARCHITECTURE_TILT * scale)
270
+ : tilt < TILT_LOW
271
+ ? TILT_LEVEL_LOW
272
+ : tilt < TILT_MEDIUM
273
+ ? TILT_LEVEL_MEDIUM
274
+ : tilt < TILT_HIGH
275
+ ? TILT_LEVEL_HIGH
276
+ : TILT_LEVEL_MAX;
277
+ return [
278
+ Math.cos(angle) * elevation,
279
+ Math.sin(angle) * elevation,
280
+ Math.sqrt(1 - elevation * elevation),
281
+ ];
282
+ };
283
+ const heightField = field;
284
+ if (influence)
285
+ lightSignal ??= paintedLightSignal(w, h, fg, foregroundArea, lum, shadingSource);
286
+ const angle = angleDeg * RADIANS_PER_DEGREE;
287
+ const lightX = Math.cos(angle) * influence * PAINTED_LIGHT_TILT_GAIN;
288
+ const lightY = Math.sin(angle) * influence * PAINTED_LIGHT_TILT_GAIN;
289
+ const normalAt = (pixel) => {
290
+ const x = pixel % w;
291
+ const y = (pixel / w) | 0;
292
+ const center = heightField[pixel];
293
+ const at = (neighbor) => (fg[neighbor] ? heightField[neighbor] : center);
294
+ const dx = (x < w - 1 ? at(pixel + 1) : center) - (x ? at(pixel - 1) : center);
295
+ const dy = (y < h - 1 ? at(pixel + w) : center) - (y ? at(pixel - w) : center);
296
+ if (!influence)
297
+ return unit([-dx * scale, dy * scale, 1]);
298
+ const tilt = lightSignal[pixel];
299
+ return unit([-dx * scale + lightX * tilt, dy * scale + lightY * tilt, 1]);
300
+ };
301
+ for (let i = 0; i < N; i++)
302
+ if (fg[i])
303
+ dirs.set(normalAt(i), i * 3);
304
+ if (needsContinuousOnly) {
305
+ cachedContinuousDirections = dirs;
306
+ }
307
+ else {
308
+ cachedContinuousDirections = includeContinuous ? dirs.slice() : null;
298
309
  const facetStrength = options.facets / PERCENT;
299
310
  // Size eligibility by the occupied footprint, then size each candidate by its own region.
300
311
  const minFacetArea = Math.max(FACET_MIN_REGION_AREA, Math.round((FACET_AREA_BASE - options.facets * FACET_AREA_SCALE) * spriteScale));
@@ -408,30 +419,119 @@ export function createNormalMapGenerator(albedo, shading) {
408
419
  }
409
420
  }
410
421
  }
422
+ if (preset === NormalMapPreset.Architecture && scale > 0)
423
+ alignStraightArchitectureEdges(dirs, fg, w, h, spriteScale, scale);
411
424
  cachedKey = key;
412
425
  directions = cachedDirections = dirs;
413
426
  }
414
- const output = new Uint8ClampedArray(N * 4);
415
- const gain = options.normalStrength / PERCENT;
416
- const ySign = options.invertY ? -1 : 1;
417
- for (let i = 0; i < N; i++) {
418
- const vector = i * 3, at = i * 4;
419
- const x = fg[i] ? directions[vector] * gain : 0;
420
- const y = fg[i] ? directions[vector + 1] * gain : 0;
421
- const z = fg[i] ? directions[vector + 2] : 1;
422
- const length = Math.sqrt(x * x + y * y + z * z) || 1;
423
- output[at] = Math.round((x / length + 1) * NORMAL_CHANNEL_SCALE);
424
- output[at + 1] = Math.round(((y / length) * ySign + 1) * NORMAL_CHANNEL_SCALE);
425
- output[at + 2] = Math.round((z / length + 1) * NORMAL_CHANNEL_SCALE);
426
- output[at + 3] = a[at + 3];
427
- }
428
- return { width: w, height: h, data: output };
427
+ }
428
+ const activeDirections = directions;
429
+ const output = new Uint8ClampedArray(N * 4);
430
+ const gain = options.normalStrength / PERCENT;
431
+ const ySign = options.invertY ? -1 : 1;
432
+ for (let i = 0; i < N; i++) {
433
+ const vector = i * 3, at = i * 4;
434
+ const x = fg[i] ? activeDirections[vector] * gain : 0;
435
+ const y = fg[i] ? activeDirections[vector + 1] * gain : 0;
436
+ const z = fg[i] ? activeDirections[vector + 2] : 1;
437
+ const length = Math.sqrt(x * x + y * y + z * z) || 1;
438
+ output[at] = Math.round((x / length + 1) * NORMAL_CHANNEL_SCALE);
439
+ output[at + 1] = Math.round(((y / length) * ySign + 1) * NORMAL_CHANNEL_SCALE);
440
+ output[at + 2] = Math.round((z / length + 1) * NORMAL_CHANNEL_SCALE);
441
+ output[at + 3] = a[at + 3];
442
+ }
443
+ return { width: w, height: h, data: output };
444
+ };
445
+ return {
446
+ setShading,
447
+ suggestPaintedLightAngle() {
448
+ return estimatePainted()?.angle ?? null;
449
+ },
450
+ generate(input = {}) {
451
+ return generateInternal(input, false);
452
+ },
453
+ generateGeometry(input = {}) {
454
+ const includeContinuous = input.includeContinuousDirections === true;
455
+ const normalMap = generateInternal(input, includeContinuous);
456
+ lightSignal ??=
457
+ foregroundArea > 0
458
+ ? paintedLightSignal(w, h, fg, foregroundArea, lum, shadingSource)
459
+ : new Float32Array(N);
460
+ return {
461
+ normalMap,
462
+ directions: cachedDirections ?? new Float32Array(N * 3),
463
+ ...(includeContinuous
464
+ ? { continuousDirections: cachedContinuousDirections ?? new Float32Array(N * 3) }
465
+ : {}),
466
+ heightField: cachedField ?? new Float32Array(N),
467
+ silhouetteDistance: distance,
468
+ thinOutline: thin,
469
+ lightSignal,
470
+ paintedLight: estimatePainted() ?? null,
471
+ segmented,
472
+ };
429
473
  },
430
474
  };
431
475
  }
432
476
  export function generateNormalMap(albedo, input = {}) {
433
477
  return createNormalMapGenerator(albedo).generate(input);
434
478
  }
479
+ // A straight exterior edge is a stronger geometry cue than the colors of individual bricks.
480
+ function alignStraightArchitectureEdges(directions, foreground, width, height, spriteScale, strength) {
481
+ const depth = Math.max(1, Math.round(spriteScale * 2));
482
+ const minLength = Math.max(ARCHITECTURE_EDGE_MIN_LENGTH, depth * 4);
483
+ const distance = new Uint8Array(foreground.length).fill(depth);
484
+ const edgeX = new Int8Array(foreground.length);
485
+ const edgeY = new Int8Array(foreground.length);
486
+ for (const horizontal of [true, false]) {
487
+ const [lineCount, lineLength] = horizontal ? [height, width] : [width, height];
488
+ const [lineStride, pixelStride] = horizontal ? [width, 1] : [1, width];
489
+ for (const side of [-1, 1]) {
490
+ for (let line = 0; line < lineCount; line++) {
491
+ const start = line * lineStride;
492
+ const outside = line + side < 0 || line + side >= lineCount;
493
+ let runStart = 0;
494
+ for (let offset = 0; offset <= lineLength; offset++) {
495
+ const pixel = start + offset * pixelStride;
496
+ if (offset < lineLength &&
497
+ foreground[pixel] &&
498
+ (outside || !foreground[pixel + side * lineStride]))
499
+ continue;
500
+ if (offset - runStart >= minLength) {
501
+ for (let along = runStart; along < offset; along++) {
502
+ for (let step = 0; step < depth; step++) {
503
+ const inside = line - step * side;
504
+ const p = inside * lineStride + along * pixelStride;
505
+ if (inside < 0 || inside >= lineCount || !foreground[p])
506
+ break;
507
+ if (step > distance[p])
508
+ continue;
509
+ if (step < distance[p]) {
510
+ distance[p] = step;
511
+ edgeX[p] = edgeY[p] = 0;
512
+ }
513
+ if (horizontal)
514
+ edgeY[p] -= side;
515
+ else
516
+ edgeX[p] += side;
517
+ }
518
+ }
519
+ }
520
+ runStart = offset + 1;
521
+ }
522
+ }
523
+ }
524
+ }
525
+ for (let p = 0; p < foreground.length; p++) {
526
+ const length = Math.hypot(edgeX[p], edgeY[p]);
527
+ if (!length)
528
+ continue;
529
+ const tilt = ARCHITECTURE_EDGE_TILT * strength * (1 - distance[p] / depth);
530
+ directions[p * 3] = (edgeX[p] * tilt) / length;
531
+ directions[p * 3 + 1] = (edgeY[p] * tilt) / length;
532
+ directions[p * 3 + 2] = Math.sqrt(1 - tilt * tilt);
533
+ }
534
+ }
435
535
  function colorEdgeDistance(a, fg, w, h) {
436
536
  const seeds = new Uint8Array(w * h);
437
537
  for (let y = 0; y < h; y++)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xprite/lighter",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Generate normal maps, light masks, and relighted renders from pixel art.",
5
5
  "license": "MIT",
6
6
  "author": "rhinoc",