GitHubEmpezar

Esta página aún no está traducida al español, por lo que se muestra la versión en inglés.

Sistemas 2D

l10n

game/l10n provides game localization built on NSGo's core package and the Go standard library: versioned YAML and JSON string tables with BCP-47 fallback and CLDR plurals, script-aware FontSet[F], RTL visual reordering and HUD mirroring, and per-language asset catalogs with selective group reloads.

import "github.com/nsgo-dev/game/pkg/l10n"

String tables, interpolation, and CLDR plurals

Load per-locale versioned YAML string tables with Catalog.LoadYAML (or flat, nested, or CLDR plural JSON tables with Catalog.LoadJSON) into a Catalog with a fallback locale, then wrap it in a reactive Localizer bound to a *core.Scope:

# yaml-language-server: $schema=https://nsgo.games/schemas/l10n.v1.json
version: 1
locale: en
strings:
  hud.score: 'Score: {score}'
  menu.play: Play
plurals:
  coins:
    zero: No coins
    one: '{count} coin'
    other: '{count} coins'
Field Meaning
version Required; must be 1 (StringTableVersion).
locale Required; normalized BCP-47 locale tag (such as en or zh-Hans).
strings Optional map of message key to localized string template.
plurals Optional map of message key to CLDR plural categories (zero, one, two, few, many, other).
cat := l10n.NewCatalog("en")
_ = cat.LoadYAML(enYAML)
_ = cat.LoadYAML(zhHansYAML)

loc := l10n.NewLocalizer(cx, cat)
loc.SetLocale("zh-Hans") // or omit to follow the system locale

title := loc.T("menu.play")
score := loc.T("hud.score", l10n.Param("score", 420))
coins := loc.Plural("coins", 3)
_, _, _ = title, score, coins

YAML decoding is strict: unknown fields, invalid plural categories, duplicate keys, keys defined in both strings and plurals, empty keys or plural maps, null values, trailing YAML documents, YAML anchors/aliases/merge keys, missing or unsupported versions (or non-decimal forms like 0x1), and non-canonical locales (such as zh_hans instead of zh-Hans) are refused without modifying the catalog. EncodeYAML and Catalog.MarshalYAML emit deterministic 2-space YAML prefixed with # yaml-language-server: $schema=https://nsgo.games/schemas/l10n.v1.json (SchemaComment) and sorted keys, so EncodeYAML(ParseYAML(b)) == b byte for byte. ParseYAML, ValidateStringTable, ApplyStringTable, and Catalog.StringTable operate directly on *StringTable values for tooling such as the editor's Localization panel.

Existing JSON string tables continue to load with Catalog.LoadJSON:

cat := l10n.NewCatalog("en")
_ = cat.LoadJSON("en", []byte(`{
	"menu": {"play": "Play"},
	"hud": {"score": "Score: {score}"},
	"coins": {"zero": "No coins", "one": "{count} coin", "other": "{count} coins"}
}`))
_ = cat.LoadJSON("zh-Hans", []byte(`{
	"menu": {"play": "开始游戏"},
	"hud": {"score": "得分:{score}"},
	"coins": {"other": "{count} 枚金币"}
}`))

Lookups walk the normalized BCP-47 fallback chain (for example zh-Hans-CN -> zh-Hans -> zh -> fallback locale) and return the key itself if missing everywhere. You can also populate entries programmatically via cat.Set and cat.SetPlural.

CLDR plural rules and dead-form auditing

Catalog.Plural, Localizer.Plural, and PluralCategoryFor evaluate integer-only cardinal plural rules generated from Unicode CLDR 48.2 (CLDRVersion, common/supplemental/plurals.xml) with no extra runtime dependency. Because Plural takes an integer count (int), CLDR's decimal and compact operands (v, w, f, t, c, e) are always treated as 0, and negative counts evaluate on their absolute value.

  • BCP-47 matching: rules match along the normalized BCP-47 subtag chain before falling back to CLDR root (other), so regional variants with distinct rules (such as pt-PT vs pt-BR) and region-qualified tags (such as cs-CZ -> cs) select the right category automatically.
  • Explicit-zero override: when count == 0 and an entry defines a non-empty zero form, Plural always selects zero regardless of whether the locale has a CLDR zero category (for example "No coins" in English). When zero is omitted, count == 0 follows the locale's CLDR rule (other in English, one in French and pt-BR, few in Romanian, many in Russian and Polish).
  • Dead-form auditing: Catalog.CheckPlurals, CheckStringTablePlurals, UnusedPluralForms, and assetcheck (game check) report any supplied plural category that the locale's integer CLDR rule never selects (for example few in English, one in Chinese, or decimal-only many in Czech and Lithuanian). zero (always reachable via the explicit-zero override) and other (the universal fallback) are never flagged. Inspect a locale's reachable integer categories directly with PluralCategories(locale).

Script-aware FontSet[F]

Pair mixed-script text with per-script or per-locale fonts (any font type F, such as *text.BitmapFont or core.Font):

fonts := l10n.NewFontSet(latinFont)
fonts.SetScript(l10n.ScriptCJK, cjkFont)
fonts.SetScript(l10n.ScriptArabic, arabicFont)
fonts.SetLocale("ja", jpFont)

// Split mixed strings into contiguous runs, each paired with its resolved font:
runs := fonts.RunsForText(loc.Locale(), "Score: 120 得分")
for _, run := range runs {
	drawRun(run.Text, run.Font)
}

Inspect scripts directly with RuneScript, DetectScript, SegmentByScript, and LocaleScript.

Baking bitmap fonts from string tables

Instead of maintaining a manual CJK or localized character list in game.yaml, point a font target's charsFrom at your YAML or JSON string tables (and optionally charsFile for extra characters). go tool game assets strips {placeholders} and rich-text markup, merges all string and plural forms with chars, and rebakes the font only when the resulting sorted character set changes; it also warns when the source font file itself lacks a collected character. go tool game check verifies that every string and plural form in a locale's tables can be drawn by the font target meant for that locale (see Command Line). In Go tooling, l10n.StripPlaceholders, StringTable.CollectChars, and l10n.ValidateLocale expose the same helpers directly.

The asset-build and asset-check paths use the same sorted character-set contract, so a table edit that adds no rune leaves a cached font up to date, while a missing rune is reported with its localization key and source line.

RTL visual ordering and layout mirroring

Query text direction from a locale (LocaleDirection), scope (EnvDirection), or string (TextDirection). For custom canvas text renderers that draw glyphs left-to-right, convert logical strings to visual order with VisualOrder (or loc.Visual(s)):

dir := loc.Direction()
visual := loc.Visual(loc.T("hud.greeting"))
aligned := l10n.LayoutAlignment("start", dir) // "left" in LTR, "right" in RTL

x := l10n.MirrorX(16, iconW, screenW, dir)
_, _, _ = visual, aligned, x

Arabic and other joining scripts need shaping, which VisualOrder does not provide: it only reorders runes, so bitmap or SDF glyphs drawn one by one come out as disconnected letters. Use platform text rendering such as DrawPlatform for those scripts.

Rich text uses the same TextDirection and grapheme-cluster rules after it wraps each line. Use text.DirectionAuto to follow the first strong character or set text.DirectionLTR/text.DirectionRTL when a screen declares its base direction.

ReadingOrder(count, rtl) returns the indices of count items in visual reading order, reversed for RTL, for custom controls that lay out or focus a row of items; mirror each item's position with MirrorX.

Per-language asset catalogs

Manage localized voiceovers, textures, or title banners with AssetCatalog, discovered automatically from an io/fs.FS (locales/<locale>/<name>, <name>.<locale>.<ext>, or <name>_<locale>.<ext>) or loaded from a YAML asset manifest:

assets, err := l10n.DiscoverFS(embedFS, "en")
if err != nil {
	return err
}
assets.RegisterGroup("voice", "voice/intro.wav", "voice/boss.wav")

// Reload only asset groups whose resolved paths actually change on language switch:
stop := assets.OnReload(func(groups []string, locale string) {
	reloadAssetGroups(groups, locale)
})
defer stop()

assets.SetLocale("ja")
resolved, ok := assets.Resolve("voice/intro.wav", assets.Locale())
_, _ = resolved, ok

// Audit missing variants in tests or CI:
for _, rep := range assets.CheckMissing("ja", "zh-Hans", "ar") {
	if !rep.Complete() {
		log.Printf("%s missing %v (%.0f%%)", rep.Locale, rep.Missing, rep.Coverage*100)
	}
}

Use assets.WatchLocale(cx, localeSignal, reloadFn) to connect locale changes directly to a reactive core.Signal[string].

Asset manifests

An asset manifest is a versioned YAML file that lists each logical asset's per-locale paths and the groups to reload on a language switch:

version: 1
base_locale: en
assets:
  voice/intro.wav:
    en: locales/en/voice/intro.wav
    ja: locales/ja/voice/intro.wav
    zh-Hans: locales/zh-Hans/voice/intro.wav
groups:
  voice:
    - voice/intro.wav
Field Meaning
version Required; must be 1.
base_locale Optional fallback locale; replaces the catalog's base locale when set.
assets Logical asset name to a map of locale to path. Each asset has at least one variant and no empty path.
groups Group name to the asset names it reloads, without duplicates. A group may name assets listed elsewhere, such as ones found by DiscoverFS.

Load one into a catalog with LoadAssetManifestYAML, which merges it over what the catalog already holds, and write a catalog back with MarshalAssetManifestYAML:

if err := assets.LoadAssetManifestYAML(data); err != nil {
	return err
}
out, err := assets.MarshalAssetManifestYAML()

Decoding is strict: an unknown field, a duplicate key, a second YAML document, a missing or unsupported version or one not written as 1 (such as 1.0 or 0x1), YAML anchors, aliases and << merge keys, an unclean asset name such as ./ui/a.png, or a locale that is not a normalized BCP-47 tag such as zh_hans (write zh-Hans) is refused with an error that names it, and nothing is merged. Output is deterministic: fields in schema order, keys sorted, group members sorted and no timestamps, so a manifest that was saved this way loads and saves back byte for byte. Saving writes this canonical form rather than the input's text, so the first save of a hand-written manifest drops comments and rewrites flow style, quoting, ordering and empty assets or groups entries; every save after that leaves the file unchanged. ParseAssetManifest, ValidateAssetManifest, EncodeAssetManifest, ApplyAssetManifest and AssetCatalog.AssetManifest work on the AssetManifest value directly for tools that edit manifests.

The localization YAML loader has a fuzz target that checks parser safety and canonical encode/parse round trips for accepted documents.

CSV exchange

ExportCSV and ImportCSV exchange deterministic key/locale tables, while ValidatePlaceholders catches dropped {name} parameters before translations are merged.

Locale-aware formatting

Use FormatNumber, FormatPercent, FormatDuration, and LanguageName for localized values and language pickers while preserving plain {name} substitutions.

Pseudolocalization

l10n.PseudoLocale(text) replaces Latin vowels with accented capitals and wraps the result in brackets ("Save {name}" becomes "[SÅvË {name}]"), so hard-coded strings, missing glyphs and clipped ends stand out in UI review. {name} placeholders and the escaped braces {{ and }} are copied unchanged, so the result still substitutes its parameters. It does not lengthen the text, so it does not by itself show where longer translations overflow.

Editar esta página