Skip to content

ReStreet: FIFA Street (2012) recompiled for Windows PC, with online play, a launcher with friends, chat and rooms. Bring your own game.

Add DualSense (PS5) button patch tool

Shadowtampa7ed14f8ed235
diff --git a/Tools/ReStreetAssetScan/DualSense.cs b/Tools/ReStreetAssetScan/DualSense.cs
new file mode 100644
index 0000000..2693c53
--- /dev/null
+++ b/Tools/ReStreetAssetScan/DualSense.cs
@@ -0,0 +1,560 @@
+using System.Buffers.Binary;
+using System.Text;
+
+namespace ReStreetAssetScan;
+
+// Swaps FIFA Street's Xbox 360 button art for DualSense art, inside the user's own game files.
+//
+// preview <game folder> <output> --controller ps5 writes before/after PNGs, touches nothing
+// apply <game folder> --controller ps5 patches data0.big and data1.big (and their .bh indexes)
+// revert <game folder> puts both archives back exactly as they were
+// status <game folder> says which controller art is applied
+// --art <folder> use the PNGs found there instead of the bundled ones
+//
+// The controller is one byte (Controller below); it is stored in the backup so the install
+// records what was applied. Only the PS5 DualSense art exists so far.
+//
+// Menu and HUD prompts: the game's own texture is kept (outline, shading, padding) and only the
+// symbol inside its black face is repainted with a glyph from the DualSense folder.
+// Skill-move pictures: the game ships a PS3 set next to the Xbox one, so the Xbox entries are
+// pointed at the PS3 data, and the in-match copy (proxy/art/tricks.big) is rebuilt from them.
+//
+// Changed entries are appended to the archive and the directory is rewritten, as the installer's
+// credit patch does. Before the first write the original directory, index and file length are
+// saved to "<archive>.dualsense-backup", which is all "revert" needs.
+internal static class DualSense
+{
+ // Which PlayStation pad the art is for. The value is the byte stored in the backup.
+ internal enum Controller : byte { PS4 = 0x04, PS5 = 0x05 }
+
+ static readonly Controller[] Available = { Controller.PS5 };
+
+ static Controller ParseController(string? value)
+ {
+ Program.Require(value is not null, "Pass --controller ps5 (the PS5 DualSense art).");
+ Controller controller = value!.Trim().ToLowerInvariant() switch
+ {
+ "ps5" or "dualsense" or "5" or "0x05" => Controller.PS5,
+ "ps4" or "dualshock4" or "ds4" or "4" or "0x04" => Controller.PS4,
+ _ => throw new InvalidDataException($"Unknown controller \"{value}\"; use ps5."),
+ };
+ Program.Require(Available.Contains(controller), $"{Describe(controller)} art is not available yet; use --controller ps5.");
+ return controller;
+ }
+
+ internal static string Describe(Controller controller) => controller switch
+ {
+ Controller.PS5 => "PS5 DualSense",
+ Controller.PS4 => "PS4 DualShock 4",
+ _ => $"controller 0x{(byte)controller:x2}",
+ };
+
+ const string Art = "data/ui/external/ion_sports07/platform/proxy/art/";
+ const string Tricks = "data/ui/imgassets/tricks/";
+
+ // (archive inside data0.big, texture entry, glyph)
+ static readonly (string Big, string Entry, string Glyph)[] Prompts =
+ {
+ ("a.big", "2", "cross"), ("b.big", "2", "circle"), ("x.big", "2", "square"), ("y.big", "2", "triangle"),
+ ("lb.big", "2", "l1"), ("rb.big", "2", "r1"), ("lt.big", "2", "l2"), ("rt.big", "2", "r2"),
+ ("lbrb.big", "2", "l1"), ("lbrb.big", "5", "r1"), ("ltrt.big", "2", "l2"), ("ltrt.big", "5", "r2"),
+ ("l3.big", "2", "l3"), ("r3.big", "2", "r3"),
+ ("las.big", "2", "l"), ("las_all.big", "2", "l"), ("las_d.big", "2", "l"), ("las_l.big", "2", "l"), ("las_lr.big", "2", "l"),
+ ("las_none.big", "2", "l"), ("las_r.big", "2", "l"), ("las_u.big", "2", "l"), ("las_ud.big", "2", "l"),
+ ("ras.big", "2", "r"), ("ras_all.big", "2", "r"), ("ras_d.big", "2", "r"), ("ras_l.big", "2", "r"), ("ras_lr.big", "2", "r"),
+ ("ras_none.big", "2", "r"), ("ras_r.big", "2", "r"), ("ras_u.big", "2", "r"), ("ras_ud.big", "2", "r"),
+ ("start.big", "2", "options"), ("select.big", "2", "create"), ("hud.big", "2", "ps"),
+ };
+
+ // Select Sides controller art: (archive inside data1.big, texture entry -> PNG in DualSense/).
+ static readonly (string Big, Dictionary<string, string> Textures)[] Controllers =
+ {
+ (Art + "controllers.big", new() { ["5"] = "controller.png", ["2"] = "controller_bar.png" }),
+ ("data/ui/game/components/fifasideselector.big",
+ new() { ["33"] = "sideselector.png", ["30"] = "sideselector_bar.png", ["8"] = "sideselector_silhouette.png" }),
+ };
+
+ // Screens that draw the controller with call-out lines (archives inside data1.big). Each has an
+ // Xbox and a PS3 layout chosen by PLATFORM == "PS3"; pointing their "PS3" constant at "XENON"
+ // makes them take the PS3 one (DualShock picture and its lines), which matches a DualSense.
+ static readonly string[] PlayStationLayoutScreens =
+ {
+ "data/ui/game/screens/settings/controllersetup.big",
+ "data/ui/game/screens/settings/controllerconfiguration.big",
+ // These embed both pictures (Xbox 360 and DualShock 3) instead of loading them by path.
+ "data/ui/game/overlays/overlay_79.big", // loading screen: controls + tips
+ "data/ui/game/overlays/overlay_87.big", // loading screen: controls + tips (second variant)
+ "data/ui/game/screens/misc/ingamemanual.big", // pause menu > Game Manual
+ };
+
+ // The DualShock 3 photo the PlayStation layout's lines point at: (archive in data1.big, texture
+ // entry, art). Built by controls_from_image.py; without that art the photo stays.
+ static readonly (string Big, string Entry, string Art)[] ControlsPictures =
+ {
+ ("data/ui/game/overlays/overlay_79.big", "74", "controls.png"),
+ ("data/ui/game/overlays/overlay_87.big", "80", "controls.png"),
+ ("data/ui/game/screens/misc/ingamemanual.big", "17", "controls.png"),
+ ("data/ui/artassets/controllerimage/controller_ps3.big", "2", "controls_large.png"),
+ };
+
+ // How much of the black face a glyph may fill.
+ static double Fill(string glyph) => glyph switch
+ {
+ "cross" or "circle" or "square" or "triangle" => 0.6,
+ "options" or "create" => 0.5,
+ "l3" or "r3" => 0.56,
+ "l1" or "r1" or "l2" or "r2" => 0.64,
+ _ => 0.72,
+ };
+
+ internal static int Run(string mode, string game, string? output, string? artFolder, string? controllerFlag)
+ {
+ try
+ {
+ Program.Require(Directory.Exists(game), $"Folder not found: {game}");
+ string data0 = Path.Combine(game, "data0.big"), data1 = Path.Combine(game, "data1.big");
+ Program.Require(File.Exists(data0) && File.Exists(data1), "data0.big and data1.big were not found; pass the ReStreet Game folder.");
+ switch (mode)
+ {
+ case "preview":
+ Program.Require(output is not null, "Missing output folder.");
+ var previewed = ParseController(controllerFlag);
+ Directory.CreateDirectory(output!);
+ Patch(data0, data1, output, write: false, artFolder, previewed);
+ return 0;
+ case "apply":
+ var controller = ParseController(controllerFlag);
+ if (Archive.HasBackup(data0) || Archive.HasBackup(data1))
+ {
+ var before = Archive.AppliedController(data0);
+ Console.WriteLine($"{(before is null ? "PlayStation" : Describe(before.Value))} art is already applied; restoring the originals first.");
+ Archive.Revert(data0); Archive.Revert(data1);
+ }
+ Patch(data0, data1, null, write: true, artFolder, controller);
+ Console.WriteLine($"{Describe(controller)} art applied (controller byte 0x{(byte)controller:x2}). Undo with: dualsense revert <game folder>");
+ return 0;
+ case "status":
+ if (!Archive.HasBackup(data0) && !Archive.HasBackup(data1)) { Console.WriteLine("Original Xbox art (nothing applied)."); return 0; }
+ var applied = Archive.AppliedController(data0) ?? Archive.AppliedController(data1);
+ Console.WriteLine(applied is null ? "PlayStation art applied by an older patcher (controller not recorded)."
+ : $"{Describe(applied.Value)} art applied (controller byte 0x{(byte)applied.Value:x2}).");
+ return 0;
+ case "revert":
+ bool any = Archive.Revert(data0) | Archive.Revert(data1);
+ Console.WriteLine(any ? "Original Xbox art restored." : "Nothing to revert.");
+ return 0;
+ default:
+ Console.Error.WriteLine("dualsense preview|apply|revert|status <game folder> [output] --controller ps5");
+ return 2;
+ }
+ }
+ catch (Exception e) { Console.Error.WriteLine("error: " + e.Message); return 1; }
+ }
+
+ static void Patch(string data0, string data1, string? preview, bool write, string? artFolder, Controller controller)
+ {
+ // Art files come from --art when it has them, otherwise from the DualSense folder next to the tool.
+ if (artFolder is not null) Program.Require(Directory.Exists(artFolder), $"Art folder not found: {artFolder}");
+ string Find(string file) => artFolder is not null && File.Exists(Path.Combine(artFolder, file))
+ ? Path.Combine(artFolder, file) : Path.Combine(AppContext.BaseDirectory, "DualSense", file);
+ var cache = new Dictionary<string, (byte[] Rgba, int Width, int Height)>();
+
+ using (var archive = Archive.Open(data0, write))
+ {
+ foreach (var group in Prompts.GroupBy(p => p.Big))
+ {
+ string name = Art + group.Key;
+ byte[] inner = Program.Decode(archive.Read(name));
+ var entries = Program.Index(inner, inner.Length).ToDictionary(e => e.Name);
+ var replaced = new Dictionary<string, byte[]>();
+ foreach (var prompt in group)
+ {
+ if (!cache.TryGetValue(prompt.Glyph, out var glyph))
+ cache[prompt.Glyph] = glyph = Textures.ReadPng(File.ReadAllBytes(Find(prompt.Glyph + ".png")));
+ var entry = entries[prompt.Entry];
+ byte[] xpr = Program.Decode(inner.AsSpan(entry.Offset, entry.Length).ToArray());
+ var texture = Textures.FirstXpr2Texture(xpr) ?? throw new InvalidDataException($"{name}!{prompt.Entry} is not a texture.");
+ byte[] before = texture.Read(xpr), after = (byte[])before.Clone();
+ Program.Require(Repaint(after, texture.Width, texture.Height, glyph, Fill(prompt.Glyph)), $"{name}!{prompt.Entry}: no button face found.");
+ texture.Write(xpr, after);
+ replaced[prompt.Entry] = xpr;
+ Preview(preview, $"{Path.GetFileNameWithoutExtension(group.Key)}_{prompt.Entry}", texture, before, texture.Read(xpr));
+ }
+ archive.Replace(name, Rebuild(inner, replaced));
+ }
+ if (write) archive.Commit(controller);
+ }
+ Console.WriteLine($"{Prompts.Length} button prompts repainted.");
+
+ using (var archive = Archive.Open(data1, write))
+ {
+ // Skill-move list: point every xenon picture at its PS3 twin.
+ var pictures = new Dictionary<int, (byte[] Xenon, byte[] Ps3)>();
+ int aliased = 0;
+ foreach (string xenon in archive.Names.Where(n => n.StartsWith(Tricks + "xenon/", StringComparison.OrdinalIgnoreCase)).ToList())
+ {
+ string ps3 = Tricks + "ps3/" + xenon[(Tricks.Length + "xenon/".Length)..];
+ if (!archive.Contains(ps3)) continue;
+ string file = Path.GetFileName(xenon);
+ if (file.StartsWith("trick_") && int.TryParse(file[6..file.IndexOf('_', 6)], out int number))
+ pictures[number] = (Program.Decode(archive.Read(xenon)), Program.Decode(archive.Read(ps3)));
+ archive.Alias(xenon, ps3); aliased++;
+ }
+
+ // In-match hints: texture 2k of tricks.big is skill move 38 + k. Moving the PS3 picture's
+ // difference from the Xbox one onto the in-match texture keeps its brighter arrows.
+ string name = Art + "tricks.big";
+ byte[] inner = Program.Decode(archive.Read(name));
+ var replacedTricks = new Dictionary<string, byte[]>();
+ foreach (var entry in Program.Index(inner, inner.Length))
+ {
+ if (!int.TryParse(entry.Name, out int id) || id % 2 != 0 || !pictures.TryGetValue(38 + id / 2, out var picture)) continue;
+ byte[] xpr = Program.Decode(inner.AsSpan(entry.Offset, entry.Length).ToArray());
+ var texture = Textures.FirstXpr2Texture(xpr);
+ var xenon = Textures.DecodeDds(picture.Xenon); var ps3 = Textures.DecodeDds(picture.Ps3);
+ if (texture is null || xenon is null || ps3 is null || xenon.Value.Width != texture.Width || xenon.Value.Height != texture.Height
+ || ps3.Value.Width != texture.Width || ps3.Value.Height != texture.Height)
+ { Console.Error.WriteLine($"warning: tricks.big!{entry.Name} skipped (size mismatch)"); continue; }
+ byte[] before = texture.Read(xpr), after = new byte[before.Length];
+ for (int i = 0; i < after.Length; i++) after[i] = (byte)Math.Clamp(before[i] + ps3.Value.Rgba[i] - xenon.Value.Rgba[i], 0, 255);
+ texture.Write(xpr, after);
+ replacedTricks[entry.Name] = xpr;
+ Preview(preview, $"tricks_{entry.Name}", texture, before, texture.Read(xpr));
+ }
+ archive.Replace(name, Rebuild(inner, replacedTricks));
+ Console.WriteLine($"{aliased} skill-move pictures switched to the PS3 set, {replacedTricks.Count} in-match hints rebuilt.");
+
+ // Select Sides: each controller set is a pad, the strip tinted with the player's colour
+ // and (offline screen) the empty-slot silhouette, replaced whole with DualSense art.
+ foreach (var (big, textures) in Controllers)
+ {
+ name = big;
+ inner = Program.Decode(archive.Read(name));
+ var replaced = new Dictionary<string, byte[]>();
+ foreach (var entry in Program.Index(inner, inner.Length))
+ {
+ if (!textures.TryGetValue(entry.Name, out string? art)) continue;
+ byte[] xpr = Program.Decode(inner.AsSpan(entry.Offset, entry.Length).ToArray());
+ var texture = Textures.FirstXpr2Texture(xpr) ?? throw new InvalidDataException($"{name}!{entry.Name} is not a texture.");
+ var image = Textures.ReadPng(File.ReadAllBytes(Find(art)));
+ Program.Require(image.Width == texture.Width && image.Height == texture.Height, $"{art} must be {texture.Width}x{texture.Height}.");
+ byte[] before = texture.Read(xpr);
+ texture.Write(xpr, image.Rgba);
+ replaced[entry.Name] = xpr;
+ Preview(preview, $"{Path.GetFileNameWithoutExtension(big)}_{entry.Name}", texture, before, texture.Read(xpr));
+ }
+ Program.Require(replaced.Count == textures.Count, $"{big} does not have the expected textures.");
+ archive.Replace(name, Rebuild(inner, replaced));
+ }
+ Console.WriteLine("Select Sides controller replaced with a DualSense.");
+
+ // Controls screens: PlayStation layout, and the DualShock 3 photo its lines point at
+ // replaced with the controls art when there is one (it is made from your own picture).
+ bool havePicture = ControlsPictures.All(p => File.Exists(Find(p.Art)));
+ int replacedPictures = 0;
+ foreach (string screen in PlayStationLayoutScreens.Concat(ControlsPictures.Select(p => p.Big)).Distinct())
+ {
+ name = screen;
+ inner = Program.Decode(archive.Read(name));
+ var entries = Program.Index(inner, inner.Length).ToDictionary(e => e.Name);
+ var replaced = new Dictionary<string, byte[]>();
+ if (PlayStationLayoutScreens.Contains(screen))
+ {
+ byte[] table = Program.Decode(inner.AsSpan(entries["1"].Offset, entries["1"].Length).ToArray());
+ replaced["1"] = RepointConstant(table, "PS3", "XENON");
+ }
+ foreach (var (_, entryName, art) in havePicture ? ControlsPictures.Where(p => p.Big == screen) : Enumerable.Empty<(string, string, string)>())
+ {
+ var entry = entries[entryName];
+ byte[] xpr = Program.Decode(inner.AsSpan(entry.Offset, entry.Length).ToArray());
+ var texture = Textures.FirstXpr2Texture(xpr) ?? throw new InvalidDataException($"{name}!{entryName} is not a texture.");
+ var image = Textures.ReadPng(File.ReadAllBytes(Find(art)));
+ Program.Require(image.Width == texture.Width && image.Height == texture.Height, $"{art} must be {texture.Width}x{texture.Height}.");
+ byte[] before = texture.Read(xpr);
+ texture.Write(xpr, image.Rgba);
+ replaced[entryName] = xpr;
+ Preview(preview, $"{Path.GetFileNameWithoutExtension(screen)}_{entryName}", texture, before, texture.Read(xpr));
+ replacedPictures++;
+ }
+ if (replaced.Count > 0) archive.Replace(name, Rebuild(inner, replaced));
+ }
+ if (write) archive.Commit(controller);
+ Console.WriteLine($"{PlayStationLayoutScreens.Length} controls screens switched to their PlayStation layout" +
+ (havePicture ? $", {replacedPictures} controller pictures replaced." : " (no controls art: they keep the DualShock 3 photo)."));
+ }
+ }
+
+ // Writes a nested BIG again with some entries replaced (stored uncompressed, which the game
+ // accepts, as the credit patch shows); the other entries keep their original bytes.
+ static byte[] Rebuild(byte[] original, Dictionary<string, byte[]> replaced)
+ {
+ var entries = Program.Index(original, original.Length);
+ int headerLength = 16 + entries.Sum(e => 9 + Encoding.UTF8.GetByteCount(e.Name));
+ using var output = new MemoryStream();
+ output.SetLength((headerLength + 63) & ~63); output.Position = output.Length;
+ var header = new byte[headerLength];
+ Buffer.BlockCopy(original, 0, header, 0, 4);
+ BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(8), (uint)entries.Count);
+ BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(12), (uint)headerLength);
+ int p = 16;
+ foreach (var e in entries)
+ {
+ byte[] data = replaced.TryGetValue(e.Name, out var changed) ? changed : original.AsSpan(e.Offset, e.Length).ToArray();
+ byte[] name = Encoding.UTF8.GetBytes(e.Name);
+ BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(p), (uint)output.Position);
+ BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(p + 4), (uint)data.Length);
+ name.CopyTo(header, p + 8); p += 9 + name.Length;
+ output.Write(data); output.Write(new byte[(int)((-output.Position) & 63)]);
+ }
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(4), (uint)output.Length);
+ output.Position = 0; output.Write(header);
+ return output.ToArray();
+ }
+
+ // An Apt constant file ("Apt constant file\x1a\0\0", then big-endian data offset, item count and
+ // item table offset; items are (type, value) pairs, type 1 a string at offset value). The string
+ // the item named `from` points at is replaced by `to`, appended at the end of the file.
+ static byte[] RepointConstant(byte[] table, string from, string to)
+ {
+ Program.Require(table.Length > 32 && Encoding.ASCII.GetString(table, 0, 17) == "Apt constant file", "Not an Apt constant file.");
+ int count = (int)Program.U(table, 24), items = (int)Program.U(table, 28);
+ string Text(int at) { int end = Array.IndexOf(table, (byte)0, at); return Encoding.Latin1.GetString(table, at, end - at); }
+ var matches = new List<int>();
+ for (int i = 0; i < count; i++)
+ {
+ int item = items + 8 * i, value = (int)Program.U(table, item + 4);
+ if (Program.U(table, item) == 1 && value < table.Length && Text(value) == from) matches.Add(item);
+ }
+ Program.Require(matches.Count == 1, $"Expected one \"{from}\" constant, found {matches.Count}.");
+ int at = (table.Length + 3) & ~3;
+ var result = new byte[at + ((to.Length + 1 + 3) & ~3)];
+ table.CopyTo(result, 0);
+ Encoding.ASCII.GetBytes(to).CopyTo(result, at);
+ BinaryPrimitives.WriteUInt32BigEndian(result.AsSpan(matches[0] + 4), (uint)at);
+ return result;
+ }
+
+ static void Preview(string? folder, string name, Textures.XenosTexture texture, byte[] before, byte[] after)
+ {
+ if (folder is null) return;
+ File.WriteAllBytes(Path.Combine(folder, name + "_before.png"), Textures.ToPng(before, texture.Width, texture.Height));
+ File.WriteAllBytes(Path.Combine(folder, name + "_after.png"), Textures.ToPng(after, texture.Width, texture.Height));
+ }
+
+ // ---- Repainting a prompt ----------------------------------------------------------------
+
+ // Finds the black face of the prompt (the dark area enclosed by its light outline), clears the
+ // Xbox symbol in it and draws the glyph centred in the face.
+ static bool Repaint(byte[] rgba, int width, int height, (byte[] Rgba, int Width, int Height) glyph, double fill)
+ {
+ int n = width * height;
+ bool Dark(int i) => rgba[i * 4 + 3] > 128 && rgba[i * 4] + rgba[i * 4 + 1] + rgba[i * 4 + 2] < 3 * 120;
+ bool Bright(int i) => rgba[i * 4 + 3] > 128 && rgba[i * 4] + rgba[i * 4 + 1] + rgba[i * 4 + 2] > 3 * 150;
+
+ // Everything reachable from the border without crossing a dark texel is outside the face.
+ var outside = new bool[n];
+ var queue = new Queue<int>();
+ for (int i = 0; i < n; i++)
+ if ((i % width == 0 || i % width == width - 1 || i / width == 0 || i / width == height - 1) && !Dark(i)) { outside[i] = true; queue.Enqueue(i); }
+ Flood(queue, width, height, j => !outside[j] && !Dark(j), j => outside[j] = true);
+
+ // The enclosed area holding the most symbol texels is the face to repaint.
+ var component = new int[n]; Array.Fill(component, -1);
+ int best = -1, bestScore = 0, count = 0;
+ for (int i = 0; i < n; i++)
+ {
+ if (outside[i] || component[i] >= 0) continue;
+ int id = count++, score = 0;
+ component[i] = id; queue.Enqueue(i);
+ Flood(queue, width, height, j => !outside[j] && component[j] < 0, j => component[j] = id);
+ for (int j = 0; j < n; j++) if (component[j] == id && Bright(j)) score++;
+ if (score > bestScore) { best = id; bestScore = score; }
+ }
+ if (best < 0)
+ {
+ // The symbol touches the outline (the Guide button's logo): use the disc that fits the dark texels.
+ int x0 = width, y0 = height, x1 = -1, y1 = -1;
+ for (int i = 0; i < n; i++)
+ if (Dark(i)) { x0 = Math.Min(x0, i % width); x1 = Math.Max(x1, i % width); y0 = Math.Min(y0, i / width); y1 = Math.Max(y1, i / width); }
+ if (x1 < 0) return false;
+ double cx = (x0 + x1 + 1) / 2.0, cy = (y0 + y1 + 1) / 2.0, rx = (x1 - x0 + 1) / 2.0, ry = (y1 - y0 + 1) / 2.0;
+ best = 0;
+ for (int i = 0; i < n; i++)
+ {
+ double dx = (i % width + 0.5 - cx) / rx, dy = (i / width + 0.5 - cy) / ry;
+ component[i] = dx * dx + dy * dy <= 1 ? 0 : -1;
+ }
+ }
+
+ int minX = width, minY = height, maxX = -1, maxY = -1; long r = 0, g = 0, b = 0, dark = 0;
+ for (int i = 0; i < n; i++)
+ {
+ if (component[i] != best) continue;
+ int x = i % width, y = i / width;
+ minX = Math.Min(minX, x); maxX = Math.Max(maxX, x); minY = Math.Min(minY, y); maxY = Math.Max(maxY, y);
+ if (Dark(i)) { r += rgba[i * 4]; g += rgba[i * 4 + 1]; b += rgba[i * 4 + 2]; dark++; }
+ }
+ byte fr = (byte)(dark > 0 ? r / dark : 0), fg = (byte)(dark > 0 ? g / dark : 0), fb = (byte)(dark > 0 ? b / dark : 0);
+
+ // Glyph fitted into the face, centred.
+ double faceW = maxX - minX + 1, faceH = maxY - minY + 1;
+ double scale = Math.Min(faceW * fill / glyph.Width, faceH * fill / glyph.Height);
+ double left = minX + (faceW - glyph.Width * scale) / 2, top = minY + (faceH - glyph.Height * scale) / 2;
+ const int Samples = 4;
+ for (int i = 0; i < n; i++)
+ {
+ if (component[i] != best) continue;
+ int x = i % width, y = i / width;
+ // Keep a one-texel dark rim so the glyph never touches the outline.
+ bool rim = x == 0 || y == 0 || x == width - 1 || y == height - 1
+ || component[i - 1] != best || component[i + 1] != best || component[i - width] != best || component[i + width] != best;
+ double coverage = 0;
+ if (!rim)
+ for (int sy = 0; sy < Samples; sy++)
+ for (int sx = 0; sx < Samples; sx++)
+ {
+ int gx = (int)((x + (sx + 0.5) / Samples - left) / scale), gy = (int)((y + (sy + 0.5) / Samples - top) / scale);
+ if (gx >= 0 && gy >= 0 && gx < glyph.Width && gy < glyph.Height) coverage += glyph.Rgba[(gy * glyph.Width + gx) * 4 + 3] / 255.0;
+ }
+ coverage /= Samples * Samples;
+ rgba[i * 4] = (byte)(fr + (255 - fr) * coverage);
+ rgba[i * 4 + 1] = (byte)(fg + (255 - fg) * coverage);
+ rgba[i * 4 + 2] = (byte)(fb + (255 - fb) * coverage);
+ rgba[i * 4 + 3] = 255;
+ }
+ return true;
+ }
+
+ static void Flood(Queue<int> queue, int width, int height, Func<int, bool> canEnter, Action<int> enter)
+ {
+ while (queue.Count > 0)
+ {
+ int i = queue.Dequeue(), x = i % width, y = i / width;
+ foreach (int j in new[] { x > 0 ? i - 1 : -1, x < width - 1 ? i + 1 : -1, y > 0 ? i - width : -1, y < height - 1 ? i + width : -1 })
+ if (j >= 0 && canEnter(j)) { enter(j); queue.Enqueue(j); }
+ }
+ }
+
+ // ---- Archive editing --------------------------------------------------------------------
+
+ sealed class Archive : IDisposable
+ {
+ readonly string path, bhPath;
+ readonly FileStream file;
+ readonly byte[] header, bh;
+ readonly Dictionary<string, Program.Entry> entries;
+ readonly List<(Program.Entry Entry, byte[]? Data, Program.Entry? Target)> changes = new();
+
+ Archive(string path, bool write)
+ {
+ this.path = path; bhPath = Path.ChangeExtension(path, ".bh");
+ file = new FileStream(path, FileMode.Open, write ? FileAccess.ReadWrite : FileAccess.Read, write ? FileShare.None : FileShare.Read);
+ var start = new byte[16]; file.ReadExactly(start);
+ Program.Require(Program.IsBig(start), $"{Path.GetFileName(path)} is not a BIG archive.");
+ int tableEnd = (int)Program.U(start, 12);
+ Program.Require(tableEnd <= 8 * 1024 * 1024, "Invalid archive directory size.");
+ header = new byte[tableEnd]; start.CopyTo(header, 0); file.ReadExactly(header.AsSpan(16));
+ entries = Program.Index(header, file.Length).ToDictionary(e => e.Name, StringComparer.OrdinalIgnoreCase);
+ bh = File.ReadAllBytes(bhPath);
+ }
+
+ internal static Archive Open(string path, bool write) => new(path, write);
+ internal IEnumerable<string> Names => entries.Keys;
+ internal bool Contains(string name) => entries.ContainsKey(name);
+
+ internal byte[] Read(string name)
+ {
+ var e = entries.TryGetValue(name, out var found) ? found : throw new InvalidDataException($"{name} was not found in {Path.GetFileName(path)}.");
+ var data = new byte[e.Length]; file.Position = e.Offset; file.ReadExactly(data); return data;
+ }
+
+ internal void Replace(string name, byte[] data) => changes.Add((entries[name], data, null));
+ internal void Alias(string name, string target) => changes.Add((entries[name], null, entries[target]));
+
+ internal static string BackupPath(string path) => path + ".dualsense-backup";
+ internal static bool HasBackup(string path) => File.Exists(BackupPath(path));
+
+ // Backup layout: "RSD2", controller byte, original length (i64), directory (i32 length +
+ // bytes), index (i32 length + bytes). "RSDS" backups (first patcher) have no controller byte.
+ internal void Commit(Controller controller)
+ {
+ // The backup goes to disk first, so an interrupted patch can always be reverted.
+ var newHeader = (byte[])header.Clone(); var newBh = (byte[])bh.Clone();
+ long originalLength = file.Length;
+ using (var backup = new FileStream(BackupPath(path), FileMode.CreateNew, FileAccess.Write))
+ using (var w = new BinaryWriter(backup))
+ {
+ w.Write(Encoding.ASCII.GetBytes("RSD2")); w.Write((byte)controller); w.Write(originalLength);
+ w.Write(header.Length); w.Write(header); w.Write(bh.Length); w.Write(bh);
+ w.Flush(); backup.Flush(true);
+ }
+
+ file.Position = originalLength;
+ foreach (var (entry, data, target) in changes)
+ {
+ int offset, length;
+ if (data is not null)
+ {
+ file.Write(new byte[(int)((-file.Position) & 63)]);
+ offset = checked((int)file.Position); length = data.Length; file.Write(data);
+ }
+ else (offset, length) = (target!.Offset, target.Length);
+ int record = FindIndexRecord(entry);
+ Put(newHeader, entry.TablePosition, offset); Put(newHeader, entry.TablePosition + 4, length);
+ Put(newBh, record, offset); Put(newBh, record + 4, length);
+ }
+ BinaryPrimitives.WriteUInt32LittleEndian(newHeader.AsSpan(4, 4), checked((uint)file.Length));
+ file.Flush(true);
+ file.Position = 0; file.Write(newHeader); file.Flush(true);
+ File.WriteAllBytes(bhPath, newBh);
+ }
+
+ int FindIndexRecord(Program.Entry e)
+ {
+ var matches = new List<int>();
+ for (int i = 16; i + 8 <= bh.Length; i += 20) if (Program.U(bh, i) == e.Offset && Program.U(bh, i + 4) == e.Length) matches.Add(i);
+ Program.Require(matches.Count == 1, $"The {Path.GetFileName(bhPath)} index does not match {e.Name}.");
+ return matches[0];
+ }
+
+ static void Put(byte[] b, int p, int v) => BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(p, 4), checked((uint)v));
+
+ internal static bool Revert(string path)
+ {
+ string backupPath = BackupPath(path);
+ if (!File.Exists(backupPath)) return false;
+ using (var r = new BinaryReader(File.OpenRead(backupPath)))
+ {
+ ReadBackupStart(r, backupPath);
+ long length = r.ReadInt64();
+ byte[] header = r.ReadBytes(r.ReadInt32()), bh = r.ReadBytes(r.ReadInt32());
+ using (var file = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
+ {
+ Program.Require(file.Length >= length, $"{Path.GetFileName(path)} is shorter than before the patch; it was replaced, not reverting.");
+ file.Write(header); file.SetLength(length); file.Flush(true);
+ }
+ File.WriteAllBytes(Path.ChangeExtension(path, ".bh"), bh);
+ }
+ File.Delete(backupPath);
+ return true;
+ }
+
+ // Reads the magic and, for "RSD2", the controller byte; leaves the reader at the length.
+ static Controller? ReadBackupStart(BinaryReader r, string backupPath)
+ {
+ string magic = Encoding.ASCII.GetString(r.ReadBytes(4));
+ if (magic == "RSDS") return null;
+ Program.Require(magic == "RSD2", $"{Path.GetFileName(backupPath)} is not a DualSense backup.");
+ return (Controller)r.ReadByte();
+ }
+
+ internal static Controller? AppliedController(string path)
+ {
+ if (!HasBackup(path)) return null;
+ using var r = new BinaryReader(File.OpenRead(BackupPath(path)));
+ return ReadBackupStart(r, BackupPath(path));
+ }
+
+ public void Dispose() => file.Dispose();
+ }
+}
diff --git a/Tools/ReStreetAssetScan/DualSense/circle.png b/Tools/ReStreetAssetScan/DualSense/circle.png
new file mode 100644
index 0000000..4136378
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/circle.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/controller.png b/Tools/ReStreetAssetScan/DualSense/controller.png
new file mode 100644
index 0000000..f36f59e
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/controller.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/controller_bar.png b/Tools/ReStreetAssetScan/DualSense/controller_bar.png
new file mode 100644
index 0000000..95f6d6a
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/controller_bar.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/controls_from_image.py b/Tools/ReStreetAssetScan/DualSense/controls_from_image.py
new file mode 100644
index 0000000..ad76fb5
--- /dev/null
+++ b/Tools/ReStreetAssetScan/DualSense/controls_from_image.py
@@ -0,0 +1,79 @@
+"""Builds the controls-screen pictures (the ones with call-out lines) from your own controller picture.
+
+On the PlayStation layout of those screens the lines end on the buttons of the game's DualShock 3
+photo. The picture is scaled (uniformly, or very nearly so) and moved so that its buttons land on
+those ends as closely as possible, while it stays inside the part of the texture the game draws.
+
+ python Tools/ReStreetAssetScan/DualSense/controls_from_image.py <cutout.png> <points.json> <output folder>
+
+points.json gives the picture's button centres in pixels, for example
+ {"L2": [210, 40], "L1": [200, 130], "R2": [1010, 40], "R1": [1020, 130], "D-pad": [208, 355],
+ "Triangle": [1012, 285], "Square": [918, 362], "Circle": [1100, 357], "Cross": [1010, 435],
+ "L3": [410, 510], "R3": [820, 510]}
+The picture should be shot from above, like the DualShock 3 photo (triggers visible behind the
+bumpers), or the shoulder and stick lines cannot meet their buttons.
+"""
+
+import json
+import os
+import sys
+
+import numpy as np
+from PIL import Image
+
+# Where each line ends, on the DualShock 3 photo of the 512x256 texture (loading screens, Game
+# Manual), measured in texels. The 1024x512 copy (controller settings) is the same photo x1.45.
+ENDS = {
+ "L2": (78, 37), "L1": (73, 61), "R2": (322, 37), "R1": (323, 60), "D-pad": (80, 152),
+ "Triangle": (328, 128), "Square": (288, 153), "Circle": (357, 155), "Cross": (320, 175),
+ "L3": (140, 205), "R3": (260, 205),
+}
+TARGETS = {
+ # name: (texture size, visible area drawn by the game, small-photo texel -> this texture)
+ "controls": ((512, 256), (400, 250), lambda x, y: (x, y)),
+}
+# The large copy draws only to y = 297, right under the photo, so fitting the whole pad there would
+# shrink it off the line ends. It takes the small fit instead; the game clips the grip tips.
+LARGE = ((1024, 512), 1.45, (14, 25), (5, 3))
+SHOULDER_WEIGHT = 0.5 # the photo's angle differs most at the shoulders; let the main buttons decide
+SS = 4
+
+source, points_file, out = sys.argv[1:4]
+os.makedirs(out, exist_ok=True)
+pad = Image.open(source).convert("RGBA")
+W, H = pad.size
+points = json.load(open(points_file, encoding="utf-8"))
+names = [n for n in ENDS if n in points]
+Q = np.array([points[n] for n in names], float)
+weights = np.array([SHOULDER_WEIGHT if n[0] in "LR" and n[1] in "12" else 1.0 for n in names])
+
+def place(file, size, sx, sy, tx, ty):
+ """Premultiplied, supersampled resize so the transparent edge gets no halo."""
+ big = pad.convert("RGBa").resize((round(W * sx * SS), round(H * sy * SS)), Image.LANCZOS)
+ canvas = Image.new("RGBa", (size[0] * SS, size[1] * SS), (0, 0, 0, 0))
+ canvas.paste(big, (round(tx * SS), round(ty * SS)))
+ canvas.resize(size, Image.LANCZOS).convert("RGBA").save(os.path.join(out, file))
+
+
+for name, (size, visible, to_texture) in TARGETS.items():
+ P = np.array([to_texture(*ENDS[n]) for n in names], float)
+ best = None
+ for sx in np.linspace(0.05, visible[0] / W, 400):
+ for aspect in np.linspace(0.92, 1.08, 17): # at most 8% squash or stretch
+ sy = sx * aspect
+ if H * sy > visible[1]:
+ continue
+ tx = np.clip(np.sum(weights * (P[:, 0] - sx * Q[:, 0])) / weights.sum(), 0, visible[0] - W * sx)
+ ty = np.clip(np.sum(weights * (P[:, 1] - sy * Q[:, 1])) / weights.sum(), 0, visible[1] - H * sy)
+ err = np.linalg.norm(np.stack([sx * Q[:, 0] + tx, sy * Q[:, 1] + ty], 1) - P, axis=1)
+ score = np.sum(weights * err) / weights.sum()
+ if best is None or score < best[0]:
+ best = (score, sx, sy, tx, ty, err)
+ score, sx, sy, tx, ty, err = best
+ place(f"{name}.png", size, sx, sy, tx, ty)
+ print(f"{name}: picture {W * sx:.0f}x{H * sy:.0f} at ({tx:.0f},{ty:.0f}) of {visible[0]}x{visible[1]} visible, "
+ f"mean error {score:.1f} texels ({', '.join(f'{n} {e:.0f}' for n, e in zip(names, err))})")
+
+ size, k, (fx, fy), (gx, gy) = LARGE
+ place("controls_large.png", size, sx * k, sy * k, (tx - fx) * k + gx, (ty - fy) * k + gy)
+ print(f"controls_large: same placement x{k} ({W * sx * k:.0f}x{H * sy * k:.0f} at ({(tx - fx) * k + gx:.0f},{(ty - fy) * k + gy:.0f}))")
diff --git a/Tools/ReStreetAssetScan/DualSense/create.png b/Tools/ReStreetAssetScan/DualSense/create.png
new file mode 100644
index 0000000..a889ebf
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/create.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/cross.png b/Tools/ReStreetAssetScan/DualSense/cross.png
new file mode 100644
index 0000000..dfa976f
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/cross.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/cutout.py b/Tools/ReStreetAssetScan/DualSense/cutout.py
new file mode 100644
index 0000000..aacb107
--- /dev/null
+++ b/Tools/ReStreetAssetScan/DualSense/cutout.py
@@ -0,0 +1,46 @@
+"""Removes a "fake transparency" checkerboard that was saved into an image's pixels.
+
+The background is flood-filled from the image border through light, neutral (grey/white) pixels;
+it stops at the subject's dark outline. Edge pixels that mix the outline with the checkerboard get
+partial alpha, so the cut-out stays smooth.
+
+ python Tools/ReStreetAssetScan/DualSense/cutout.py <input.png> <output.png>
+"""
+
+import sys
+from collections import deque
+
+from PIL import Image, ImageFilter
+
+source, target = sys.argv[1], sys.argv[2]
+image = Image.open(source).convert("RGB")
+w, h = image.size
+px = image.load()
+
+
+def checker(p, light=150):
+ return min(p) >= light and max(p) - min(p) <= 12
+
+
+outside = bytearray(w * h)
+queue = deque()
+for x in range(w):
+ for y in (0, h - 1):
+ if checker(px[x, y]): outside[y * w + x] = 1; queue.append((x, y))
+for y in range(h):
+ for x in (0, w - 1):
+ if checker(px[x, y]): outside[y * w + x] = 1; queue.append((x, y))
+while queue:
+ x, y = queue.popleft()
+ for nx, ny in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):
+ if 0 <= nx < w and 0 <= ny < h and not outside[ny * w + nx] and checker(px[nx, ny]):
+ outside[ny * w + nx] = 1; queue.append((nx, ny))
+
+alpha = Image.frombytes("L", (w, h), bytes(0 if o else 255 for o in outside))
+# Soften the cut by one pixel so the outline's anti-aliasing is kept rather than a hard step.
+alpha = alpha.filter(ImageFilter.MinFilter(3)).filter(ImageFilter.GaussianBlur(0.8))
+result = image.convert("RGBA")
+result.putalpha(alpha)
+box = alpha.point(lambda v: 255 if v > 8 else 0).getbbox()
+result.crop(box).save(target)
+print(target, "subject", box)
diff --git a/Tools/ReStreetAssetScan/DualSense/l.png b/Tools/ReStreetAssetScan/DualSense/l.png
new file mode 100644
index 0000000..b6bba81
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/l.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/l1.png b/Tools/ReStreetAssetScan/DualSense/l1.png
new file mode 100644
index 0000000..f0cc92a
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/l1.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/l2.png b/Tools/ReStreetAssetScan/DualSense/l2.png
new file mode 100644
index 0000000..7be3a01
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/l2.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/l3.png b/Tools/ReStreetAssetScan/DualSense/l3.png
new file mode 100644
index 0000000..d59cb66
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/l3.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/make_glyphs.py b/Tools/ReStreetAssetScan/DualSense/make_glyphs.py
new file mode 100644
index 0000000..ca4ad4c
--- /dev/null
+++ b/Tools/ReStreetAssetScan/DualSense/make_glyphs.py
@@ -0,0 +1,239 @@
+"""Draws the DualSense symbols the patcher paints into the game's button prompts.
+
+Each glyph is a white shape on transparency, cropped to its ink. The patcher scales it into the
+black area of the original prompt, so only the shape matters here, not the final size.
+
+ python Tools/ReStreetAssetScan/DualSense/make_glyphs.py
+"""
+
+import os
+
+from PIL import Image, ImageDraw, ImageFilter, ImageFont
+
+SIZE = 256
+STROKE = 34
+HERE = os.path.dirname(os.path.abspath(__file__))
+FONT = os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "Fonts", "arialbd.ttf")
+
+
+def canvas():
+ image = Image.new("L", (SIZE, SIZE), 0)
+ return image, ImageDraw.Draw(image)
+
+
+def cross():
+ image, draw = canvas()
+ m = STROKE // 2 + 8
+ draw.line([(m, m), (SIZE - m, SIZE - m)], fill=255, width=STROKE)
+ draw.line([(m, SIZE - m), (SIZE - m, m)], fill=255, width=STROKE)
+ return image
+
+
+def circle():
+ image, draw = canvas()
+ m = 8
+ draw.ellipse([m, m, SIZE - m, SIZE - m], outline=255, width=STROKE)
+ return image
+
+
+def square():
+ image, draw = canvas()
+ m = 24
+ draw.rectangle([m, m, SIZE - m, SIZE - m], outline=255, width=STROKE)
+ return image
+
+
+def triangle():
+ image, draw = canvas()
+ m = 8
+ top, left, right = (SIZE / 2, m + 10), (m, SIZE - m - 30), (SIZE - m, SIZE - m - 30)
+ draw.line([top, left, right, top, left], fill=255, width=STROKE, joint="curve")
+ return image
+
+
+def options():
+ # Three horizontal bars, the mark printed next to the OPTIONS button.
+ image, draw = canvas()
+ for i in range(3):
+ y = 40 + i * 80
+ draw.rounded_rectangle([20, y, SIZE - 20, y + STROKE + 4], radius=12, fill=255)
+ return image
+
+
+def create():
+ # Three short slanted strokes, the mark printed next to the CREATE button.
+ image, draw = canvas()
+ for i in range(3):
+ x = 40 + i * 80
+ draw.line([(x + 30, 30), (x - 10, SIZE - 30)], fill=255, width=STROKE + 4)
+ return image
+
+
+def text(label):
+ font = ImageFont.truetype(FONT, 220)
+ image = Image.new("L", (SIZE * 2, SIZE), 0)
+ ImageDraw.Draw(image).text((10, 0), label, font=font, fill=255)
+ return image
+
+
+GLYPHS = {
+ "cross": cross, "circle": circle, "square": square, "triangle": triangle,
+ "options": options, "create": create,
+ **{name.lower(): (lambda name=name: text(name)) for name in ["L1", "R1", "L2", "R2", "L3", "R3", "L", "R", "PS"]},
+}
+
+# ---- Select Sides controller ---------------------------------------------------------------------
+#
+# The pad is drawn once in its own design space (it uses 0..96 x 0..68) and then mapped into each
+# texture the game uses for it: texel = offset + scale * design.
+#
+# Each controller texture comes with a white strip the game tints with the player's colour and lays
+# over the bottom of the pad: strip texel (u, v) lands on controller texel (x + sx*u, y + sy*v).
+# Those mappings and the old outlines were measured in game against the Xbox 360 art.
+SS = 8 # supersampling
+TARGETS = {
+ # data1.big proxy/art/controllers.big: texture 5 (pad, 128x128) and 2 (strip, 128x32).
+ "controller": dict(size=(128, 128), box=(4, 4, 92, 64), bar=(19.0, 0.641, 49.2, 0.73), bar_size=(128, 32)),
+ # data1.big data/ui/game/components/fifasideselector.big: texture 33 (pad), 30 (strip), 8 (empty slot).
+ "sideselector": dict(size=(256, 128), box=(4, 5, 126, 88), bar=(23.95, 0.95, 67.6, 0.916), bar_size=(128, 32),
+ silhouette=dict(size=(128, 64), box=(1, 1, 90, 62), colour=(176, 180, 176, 130))),
+}
+
+
+def spline(points, steps=12):
+ """Closed Catmull-Rom curve through points."""
+ out = []
+ n = len(points)
+ for i in range(n):
+ p0, p1, p2, p3 = points[i - 1], points[i], points[(i + 1) % n], points[(i + 2) % n]
+ for s in range(steps):
+ t = s / steps
+ out.append(tuple(0.5 * ((2 * p1[k]) + (-p0[k] + p2[k]) * t + (2 * p0[k] - 5 * p1[k] + 4 * p2[k] - p3[k]) * t * t
+ + (-p0[k] + 3 * p1[k] - 3 * p2[k] + p3[k]) * t * t * t) for k in range(2)))
+ return out
+
+
+def mirrored(left):
+ """Left half (top centre to bottom centre) to a full symmetric outline around x = 48."""
+ return left + [(96 - x, y) for x, y in reversed(left[1:-1])]
+
+
+BODY = spline(mirrored([(48, 9), (34, 8.5), (20, 9.5), (12, 13), (8, 20), (6, 30), (6.5, 42), (9, 54), (13, 63), (19, 66.5),
+ (25, 64.5), (29, 59.5), (33, 57.5), (40, 56.7), (48, 56.5)]))
+CENTRE = spline(mirrored([(48, 28), (36, 28), (28, 31), (25.5, 37), (27, 46), (31, 54), (40, 56.6), (48, 56.4)]))
+DESIGN = (128, 128)
+
+
+def scaled(points):
+ return [(x * SS, y * SS) for x, y in points]
+
+
+def design_pad():
+ size = (DESIGN[0] * SS, DESIGN[1] * SS)
+ image = Image.new("RGBA", size, (0, 0, 0, 0))
+ d = ImageDraw.Draw(image)
+ body = scaled(BODY)
+ d.polygon(body, fill=(58, 60, 66, 255)) # dark rim, keeps it readable on light walls
+ inner = Image.new("L", size, 0)
+ ImageDraw.Draw(inner).polygon(body, fill=255)
+ inner = inner.filter(ImageFilter.MinFilter(2 * SS - 1)) # body shrunk by ~1 unit
+ white = Image.new("RGBA", size, (238, 239, 242, 255))
+ shade = Image.linear_gradient("L").resize(size).point(lambda v: int(v * 0.16))
+ white = Image.composite(Image.new("RGBA", size, (196, 199, 206, 255)), white, shade)
+ image.paste(white, (0, 0), inner)
+
+ # Black centre section with the sticks, as on the real pad.
+ d.polygon(scaled(CENTRE), fill=(24, 25, 29, 255))
+ # Touchpad.
+ d.rounded_rectangle([33 * SS, 9.5 * SS, 63 * SS, 27 * SS], radius=4 * SS, fill=(228, 230, 234, 255), outline=(150, 153, 160, 255), width=SS)
+ # Light bar edges either side of the touchpad.
+ for x in (31.2, 64.8):
+ d.line([(x * SS, 11 * SS), (x * SS, 25 * SS)], fill=(120, 170, 255, 255), width=int(1.2 * SS))
+ # Create and Options.
+ for x in (26.5, 69.5):
+ d.rounded_rectangle([(x - 1.2) * SS, 10.5 * SS, (x + 1.2) * SS, 15 * SS], radius=SS, fill=(70, 72, 78, 255))
+ # Sticks.
+ for x in (37.5, 58.5):
+ d.ellipse([(x - 6.2) * SS, (39.5 - 6.2) * SS, (x + 6.2) * SS, (39.5 + 6.2) * SS], fill=(8, 8, 10, 255))
+ d.ellipse([(x - 4.6) * SS, (39.5 - 4.6) * SS, (x + 4.6) * SS, (39.5 + 4.6) * SS], fill=(52, 54, 60, 255))
+ d.ellipse([(x - 3.2) * SS, (39.5 - 3.2) * SS, (x + 3.2) * SS, (39.5 + 3.2) * SS], fill=(36, 38, 42, 255))
+ # PS button and mute button.
+ d.ellipse([46 * SS, 32 * SS, 50 * SS, 36 * SS], fill=(90, 92, 98, 255))
+ d.rounded_rectangle([46.3 * SS, 46 * SS, 49.7 * SS, 47.5 * SS], radius=SS // 2, fill=(255, 140, 120, 255))
+ # D-pad.
+ cx, cy, a = 17, 23, 3.4
+ for dx, dy in ((0, -1), (0, 1), (-1, 0), (1, 0)):
+ x, y = cx + dx * a, cy + dy * a
+ d.rounded_rectangle([(x - 1.7) * SS, (y - 1.7) * SS, (x + 1.7) * SS, (y + 1.7) * SS], radius=SS // 2, fill=(70, 72, 78, 255))
+ # Face buttons, tinted like their symbols.
+ cx, cy, a = 79, 23, 4.2
+ for (dx, dy), colour in zip(((0, -1), (1, 0), (0, 1), (-1, 0)), ((70, 190, 150), (235, 90, 100), (110, 150, 235), (220, 130, 200))):
+ x, y = cx + dx * a, cy + dy * a
+ d.ellipse([(x - 2.2) * SS, (y - 2.2) * SS, (x + 2.2) * SS, (y + 2.2) * SS], fill=(62, 64, 70, 255))
+ d.ellipse([(x - 1.0) * SS, (y - 1.0) * SS, (x + 1.0) * SS, (y + 1.0) * SS], fill=colour + (255,))
+ return image
+
+
+def design_strip():
+ """A colour strip along the inside of the bottom edge of the black centre section."""
+ layer = Image.new("L", (DESIGN[0] * SS, DESIGN[1] * SS), 0)
+ edge = sorted((x, y) for x, y in CENTRE if 30 <= x <= 66 and y > 51)
+ top = [(x * SS, (y - 3.6) * SS) for x, y in edge]
+ bottom = [(x * SS, (y - 0.4) * SS) for x, y in reversed(edge)]
+ ImageDraw.Draw(layer).polygon(top + bottom, fill=255)
+ return layer
+
+
+def design_mask():
+ layer = Image.new("L", (DESIGN[0] * SS, DESIGN[1] * SS), 0)
+ ImageDraw.Draw(layer).polygon(scaled(BODY), fill=255)
+ return layer
+
+
+def fit(box):
+ """Design-to-texel mapping that lays the pad outline over box (where the old pad was)."""
+ xs, ys = [x for x, _ in BODY], [y for _, y in BODY]
+ sx, sy = (box[2] - box[0]) / (max(xs) - min(xs)), (box[3] - box[1]) / (max(ys) - min(ys))
+ return box[0] - sx * min(xs), sx, box[1] - sy * min(ys), sy
+
+
+def render(image, size, mapping):
+ """Resamples a design-space image into a texture; mapping is (ox, sx, oy, sy), texel = o + s * design."""
+ ox, sx, oy, sy = mapping
+ big = image.transform((size[0] * SS, size[1] * SS), Image.AFFINE,
+ (1 / sx, 0, -ox * SS / sx, 0, 1 / sy, -oy * SS / sy), resample=Image.BICUBIC)
+ return big.resize(size, Image.LANCZOS)
+
+
+def alpha_image(mask, colour=(255, 255, 255, 255)):
+ image = Image.new("RGBA", mask.size, colour[:3] + (0,))
+ image.putalpha(mask.point(lambda v: v * colour[3] // 255))
+ return image
+
+
+def controller_art():
+ pad, strip, mask = design_pad(), design_strip(), design_mask()
+ for name, target in TARGETS.items():
+ mapping = fit(target["box"])
+ render(pad, target["size"], mapping).save(os.path.join(HERE, f"{name}.png"), optimize=True)
+ # Strip texel (u, v) -> pad texel (bx + bsx*u, by + bsy*v) -> design (texel - o) / s.
+ bx, bsx, by, bsy = target["bar"]
+ ox, sx, oy, sy = mapping
+ bar = (ox - bx) / bsx, sx / bsx, (oy - by) / bsy, sy / bsy
+ alpha_image(render(strip, target["bar_size"], bar)).save(os.path.join(HERE, f"{name}_bar.png"), optimize=True)
+ if "silhouette" in target:
+ s = target["silhouette"]
+ alpha_image(render(mask, s["size"], fit(s["box"])), s["colour"]).save(os.path.join(HERE, f"{name}_silhouette.png"), optimize=True)
+ print(name, target["size"])
+
+
+if __name__ == "__main__":
+ for name, draw in GLYPHS.items():
+ mask = draw()
+ mask = mask.crop(mask.getbbox())
+ glyph = Image.new("RGBA", mask.size, (255, 255, 255, 0))
+ glyph.putalpha(mask)
+ glyph.save(os.path.join(HERE, f"{name}.png"), optimize=True)
+ print(name, mask.size)
+
+ controller_art()
diff --git a/Tools/ReStreetAssetScan/DualSense/options.png b/Tools/ReStreetAssetScan/DualSense/options.png
new file mode 100644
index 0000000..1d747f3
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/options.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/pad_from_image.py b/Tools/ReStreetAssetScan/DualSense/pad_from_image.py
new file mode 100644
index 0000000..cf5f6d9
--- /dev/null
+++ b/Tools/ReStreetAssetScan/DualSense/pad_from_image.py
@@ -0,0 +1,98 @@
+"""Builds the Select Sides controller textures from your own controller picture.
+
+The picture must already be a cut-out (real alpha; see cutout.py). It is fitted, without
+distortion, where the Xbox 360 pad was. The player-colour strip is made from the picture's thick
+dark parts (a DualSense's black inner grips) inside the area where the game draws the strip, and
+the empty-slot silhouette from its alpha.
+
+ python Tools/ReStreetAssetScan/DualSense/pad_from_image.py <cutout.png> <output folder> [accents|pill|none]
+
+Strip styles: "accents" colours the dark inner grips, "pill" draws a player-colour bar under the
+centre of the pad (default), "none" leaves the pad without player colour.
+
+Then patch with: ReStreetAssetScan dualsense apply <game folder> --art <output folder>
+Keep pictures you did not make yourself (and what this builds from them) out of Git.
+"""
+
+import os
+import sys
+
+from PIL import Image, ImageFilter
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from make_glyphs import SS, TARGETS # noqa: E402 (shared measured layout)
+
+source, out = sys.argv[1], sys.argv[2]
+style = sys.argv[3] if len(sys.argv) > 3 else "pill"
+os.makedirs(out, exist_ok=True)
+pad = Image.open(source).convert("RGBA")
+W, H = pad.size
+
+# Dark, thick parts of the picture: candidates for the colour strip (thin outlines are opened away).
+grey = pad.convert("L")
+alpha = pad.getchannel("A")
+dark = Image.eval(Image.merge("LA", (grey, alpha)).convert("LA").getchannel("L"), lambda v: 255 if v < 100 else 0)
+dark = Image.composite(dark, Image.new("L", pad.size, 0), alpha.point(lambda v: 255 if v > 200 else 0))
+k = max(3, (W // 90) | 1) # ~1 texel at the final size
+dark = dark.filter(ImageFilter.MinFilter(k)).filter(ImageFilter.MaxFilter(k)).filter(ImageFilter.GaussianBlur(k / 4))
+
+
+def fit(box):
+ """Picture-to-texel mapping (texel = o + s * pixel) that fits the picture into box, centred."""
+ bw, bh = box[2] - box[0], box[3] - box[1]
+ s = min(bw / W, bh / H)
+ return box[0] + (bw - s * W) / 2, box[1] + (bh - s * H) / 2, s
+
+
+def render(image, size, ax, cx, ay, cy):
+ """Resamples image into a texture of size; input pixel = a * texel + c (premultiplied, supersampled)."""
+ mode = image.mode
+ work = image.convert("RGBa") if mode == "RGBA" else image
+ big = work.transform((size[0] * SS, size[1] * SS), Image.AFFINE, (ax / SS, 0, cx, 0, ay / SS, cy), resample=Image.BILINEAR)
+ small = big.resize(size, Image.LANCZOS)
+ return small.convert("RGBA") if mode == "RGBA" else small
+
+
+for name, target in TARGETS.items():
+ ox, oy, s = fit(target["box"])
+ render(pad, target["size"], 1 / s, -ox / s, 1 / s, -oy / s).save(os.path.join(out, f"{name}.png"))
+
+ # The game only draws the strip right of bx and below by; keep it symmetric about the pad's
+ # centre and fade it in at those edges so the cut does not show.
+ bx, bsx, by, bsy = target["bar"]
+ centre = (target["box"][0] + target["box"][2]) / 2
+ left, right, fade_x, fade_y = bx + 0.5, 2 * centre - (bx + 0.5), 3.0, 4.0
+ weight = Image.new("L", pad.size, 0)
+ wp = weight.load()
+ columns = [max(0.0, min(1.0, (t - left) / fade_x, (right - t) / fade_x)) for t in (ox + s * (x + 0.5) for x in range(W))]
+ rows = [max(0.0, min(1.0, (t - by) / fade_y)) for t in (oy + s * (y + 0.5) for y in range(H))]
+ for y in range(H):
+ if rows[y] == 0: continue
+ for x in range(W):
+ if columns[x]: wp[x, y] = int(255 * rows[y] * columns[x])
+ if style == "accents":
+ masked = Image.frombytes("L", pad.size, bytes(d * w // 255 for d, w in zip(dark.tobytes(), weight.tobytes())))
+ # Strip texel (u, v) -> pad texel (bx + bsx*u, by + bsy*v) -> picture pixel (texel - o) / s.
+ strip = render(masked, target["bar_size"], bsx / s, (bx - ox) / s, bsy / s, (by - oy) / s)
+ else:
+ # A rounded bar centred under the pad, in the gap between the grips (pad texels).
+ bw = (target["box"][2] - target["box"][0]) * 0.3
+ rect = (centre - bw / 2, by + 1.5, centre + bw / 2, by + 6.0)
+ layer = Image.new("L", (target["bar_size"][0] * SS, target["bar_size"][1] * SS), 0)
+ if style == "pill":
+ from PIL import ImageDraw
+ u0, v0, u1, v1 = ((rect[0] - bx) / bsx, (rect[1] - by) / bsy, (rect[2] - bx) / bsx, (rect[3] - by) / bsy)
+ ImageDraw.Draw(layer).rounded_rectangle([u0 * SS, v0 * SS, u1 * SS, v1 * SS], radius=(v1 - v0) * SS / 2, fill=255)
+ strip = layer.resize(target["bar_size"], Image.LANCZOS)
+ bar = Image.new("RGBA", target["bar_size"], (255, 255, 255, 0))
+ bar.putalpha(strip.point(lambda v: v * 235 // 255))
+ bar.save(os.path.join(out, f"{name}_bar.png"))
+
+ if "silhouette" in target:
+ sil = target["silhouette"]
+ sx, sy, ss = fit(sil["box"])
+ mask = render(alpha, sil["size"], 1 / ss, -sx / ss, 1 / ss, -sy / ss)
+ image = Image.new("RGBA", sil["size"], sil["colour"][:3] + (0,))
+ image.putalpha(mask.point(lambda v: v * sil["colour"][3] // 255))
+ image.save(os.path.join(out, f"{name}_silhouette.png"))
+ print(name, target["size"], "scale", round(s, 4))
diff --git a/Tools/ReStreetAssetScan/DualSense/ps.png b/Tools/ReStreetAssetScan/DualSense/ps.png
new file mode 100644
index 0000000..98359a8
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/ps.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/r.png b/Tools/ReStreetAssetScan/DualSense/r.png
new file mode 100644
index 0000000..9afb22c
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/r.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/r1.png b/Tools/ReStreetAssetScan/DualSense/r1.png
new file mode 100644
index 0000000..a1c4e15
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/r1.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/r2.png b/Tools/ReStreetAssetScan/DualSense/r2.png
new file mode 100644
index 0000000..b4021df
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/r2.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/r3.png b/Tools/ReStreetAssetScan/DualSense/r3.png
new file mode 100644
index 0000000..7d44863
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/r3.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/sideselector.png b/Tools/ReStreetAssetScan/DualSense/sideselector.png
new file mode 100644
index 0000000..dca72e1
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/sideselector.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/sideselector_bar.png b/Tools/ReStreetAssetScan/DualSense/sideselector_bar.png
new file mode 100644
index 0000000..ef674bf
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/sideselector_bar.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/sideselector_silhouette.png b/Tools/ReStreetAssetScan/DualSense/sideselector_silhouette.png
new file mode 100644
index 0000000..2f95472
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/sideselector_silhouette.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/square.png b/Tools/ReStreetAssetScan/DualSense/square.png
new file mode 100644
index 0000000..918851c
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/square.png differ
diff --git a/Tools/ReStreetAssetScan/DualSense/triangle.png b/Tools/ReStreetAssetScan/DualSense/triangle.png
new file mode 100644
index 0000000..37e83dd
Binary files /dev/null and b/Tools/ReStreetAssetScan/DualSense/triangle.png differ
diff --git a/Tools/ReStreetAssetScan/EasyInstall.cs b/Tools/ReStreetAssetScan/EasyInstall.cs
new file mode 100644
index 0000000..2c1cf17
--- /dev/null
+++ b/Tools/ReStreetAssetScan/EasyInstall.cs
@@ -0,0 +1,189 @@
+using System.Diagnostics;
+using System.Text.Json;
+
+namespace ReStreetAssetScan;
+
+// Player-facing front end for the DualSense patch: finds the ReStreet install by itself, checks the
+// game is closed and runs apply / revert / status. Started with no arguments it shows a menu, so the
+// published exe (and "Instalar DualSense.cmd" / "Remover DualSense.cmd") work with a double click.
+//
+// install [ReStreet folder] apply the PS5 DualSense art (art from the DualSense folder next to the exe)
+// uninstall [ReStreet folder] restore the original Xbox art
+// status [ReStreet folder]
+internal static class EasyInstall
+{
+ internal static int Run(string[] args)
+ {
+ int result;
+ try { Console.OutputEncoding = System.Text.Encoding.UTF8; } catch (Exception) { }
+ try
+ {
+ string mode = args.Length > 0 ? args[0] : Menu();
+ if (mode == "") return 0;
+ string? folder = args.Length > 1 ? args[1] : null;
+ string game = FindGame(folder);
+ Console.WriteLine($"ReStreet encontrado: {game}");
+ Console.WriteLine();
+ if (mode != "status" && Process.GetProcessesByName("fifastreet").Length > 0)
+ throw new InvalidOperationException("O jogo está aberto. Feche o FIFA Street (o launcher pode ficar aberto) e tente de novo.");
+ result = mode switch
+ {
+ "install" => DualSense.Run("apply", game, null, null, "ps5"),
+ "uninstall" => DualSense.Run("revert", game, null, null, null),
+ "status" => DualSense.Run("status", game, null, null, null),
+ _ => throw new ArgumentException($"Opção desconhecida: {mode}"),
+ };
+ Console.WriteLine();
+ Console.WriteLine(result == 0
+ ? mode switch
+ {
+ "install" => "Pronto: o DualSense (PS5) foi aplicado. Antes de atualizar o ReStreet, use \"Remover DualSense\" e depois instale de novo.",
+ "uninstall" => "Pronto: o jogo voltou à arte original do Xbox.",
+ _ => "",
+ }
+ : "Não deu certo; veja a mensagem acima. Nada foi alterado se o erro apareceu antes de gravar.");
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine("Erro: " + e.Message);
+ result = 1;
+ }
+ Pause();
+ return result;
+ }
+
+ static string Menu()
+ {
+ Console.WriteLine("ReStreet - botões de PlayStation 5 (DualSense)");
+ Console.WriteLine();
+ Console.WriteLine(" 1 Instalar DualSense");
+ Console.WriteLine(" 2 Remover DualSense (voltar ao Xbox)");
+ Console.WriteLine(" 3 Ver o que está aplicado");
+ Console.WriteLine();
+ Console.Write("Escolha 1, 2 ou 3: ");
+ string? answer = Console.ReadLine()?.Trim();
+ Console.WriteLine();
+ return answer switch { "1" => "install", "2" => "uninstall", "3" => "status", _ => "" };
+ }
+
+ static void Pause()
+ {
+ if (Console.IsInputRedirected) return;
+ Console.WriteLine();
+ Console.Write("Pressione Enter para fechar.");
+ Console.ReadLine();
+ }
+
+ // ---- Finding the install ----------------------------------------------------------------
+
+ // The Game folder (the one with data0.big and data1.big) of a ReStreet install.
+ static string FindGame(string? given)
+ {
+ if (given is not null)
+ {
+ string path = Path.GetFullPath(given.Trim('"'));
+ return GameFolder(path) ?? throw new DirectoryNotFoundException($"\"{path}\" não parece ser uma pasta do ReStreet (não achei Game\\data0.big).");
+ }
+
+ var found = new List<string>();
+ void Add(string? root)
+ {
+ if (root is null) return;
+ string? game = GameFolder(root);
+ if (game is not null && !found.Contains(game, StringComparer.OrdinalIgnoreCase)) found.Add(game);
+ }
+
+ // 1. The exe sits inside the install (or one of its folders).
+ for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent) Add(dir.FullName);
+ // 2. The launcher shortcut the installer creates.
+ foreach (string lnk in Shortcuts()) Add(Path.GetDirectoryName(ShortcutTarget(lnk)));
+ if (found.Count == 1) return found[0];
+ // 3. A shallow look at every fixed drive.
+ if (found.Count == 0)
+ foreach (var drive in DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed && d.IsReady))
+ foreach (string root in Folders(drive.RootDirectory.FullName, depth: 3)) Add(root);
+
+ if (found.Count == 0)
+ throw new DirectoryNotFoundException("Não achei o ReStreet. Arraste a pasta do ReStreet (a que tem o FifaStreetLauncher.exe) para cima de \"Instalar DualSense.cmd\".");
+ if (found.Count == 1) return found[0];
+
+ Console.WriteLine("Achei mais de uma instalação do ReStreet:");
+ for (int i = 0; i < found.Count; i++) Console.WriteLine($" {i + 1} {found[i]}");
+ if (Console.IsInputRedirected) throw new InvalidOperationException("Mais de uma instalação; passe a pasta do ReStreet como argumento.");
+ Console.Write($"Qual delas (1-{found.Count})? ");
+ if (int.TryParse(Console.ReadLine(), out int choice) && choice >= 1 && choice <= found.Count) { Console.WriteLine(); return found[choice - 1]; }
+ throw new InvalidOperationException("Nenhuma instalação escolhida.");
+ }
+
+ // Accepts the ReStreet folder (uses the launcher's settings.json when there is one), its Game
+ // folder or an older GameData folder.
+ static string? GameFolder(string path)
+ {
+ try
+ {
+ if (!Directory.Exists(path)) return null;
+ string settings = Path.Combine(path, "settings.json");
+ if (File.Exists(settings) && File.Exists(Path.Combine(path, "FifaStreetLauncher.exe")))
+ {
+ using var json = JsonDocument.Parse(File.ReadAllText(settings));
+ if (json.RootElement.TryGetProperty("GamePath", out var gamePath) && gamePath.GetString() is string g && HasData(g)) return Path.GetFullPath(g);
+ }
+ foreach (string candidate in new[] { path, Path.Combine(path, "Game"), Path.Combine(path, "GameData") })
+ if (HasData(candidate)) return Path.GetFullPath(candidate);
+ }
+ catch (Exception) { }
+ return null;
+
+ static bool HasData(string folder) =>
+ File.Exists(Path.Combine(folder, "data0.big")) && File.Exists(Path.Combine(folder, "data1.big")) && File.Exists(Path.Combine(folder, "data1.bh"));
+ }
+
+ static IEnumerable<string> Shortcuts()
+ {
+ var places = new[]
+ {
+ Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
+ Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory),
+ Environment.GetFolderPath(Environment.SpecialFolder.Programs),
+ Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms),
+ };
+ foreach (string place in places.Where(p => p.Length > 0 && Directory.Exists(p)))
+ {
+ IEnumerable<string> links;
+ try { links = Directory.EnumerateFiles(place, "*.lnk", SearchOption.AllDirectories).Where(f => Path.GetFileName(f).Contains("ReStreet", StringComparison.OrdinalIgnoreCase)).ToList(); }
+ catch (Exception) { continue; }
+ foreach (string link in links) yield return link;
+ }
+ }
+
+ // Target of a .lnk, read from its LinkInfo local base path (MS-SHLLINK); null when absent.
+ static string? ShortcutTarget(string lnk)
+ {
+ try
+ {
+ byte[] b = File.ReadAllBytes(lnk);
+ if (b.Length < 0x4C || BitConverter.ToInt32(b, 0) != 0x4C) return null;
+ int flags = BitConverter.ToInt32(b, 0x14), p = 0x4C;
+ if ((flags & 0x01) != 0) p += 2 + BitConverter.ToUInt16(b, p); // LinkTargetIDList
+ if ((flags & 0x02) == 0) return null; // no LinkInfo
+ int localBase = BitConverter.ToInt32(b, p + 0x10);
+ int end = Array.IndexOf(b, (byte)0, p + localBase);
+ return System.Text.Encoding.Default.GetString(b, p + localBase, end - p - localBase);
+ }
+ catch (Exception) { return null; }
+ }
+
+ static IEnumerable<string> Folders(string root, int depth)
+ {
+ if (depth == 0) yield break;
+ string[] children;
+ try { children = Directory.GetDirectories(root); } catch (Exception) { yield break; }
+ foreach (string child in children)
+ {
+ string name = Path.GetFileName(child);
+ if (name.StartsWith('$') || name.Equals("Windows", StringComparison.OrdinalIgnoreCase)) continue;
+ yield return child;
+ foreach (string deeper in Folders(child, depth - 1)) yield return deeper;
+ }
+ }
+}
diff --git a/Tools/ReStreetAssetScan/Program.cs b/Tools/ReStreetAssetScan/Program.cs
new file mode 100644
index 0000000..d5b5890
--- /dev/null
+++ b/Tools/ReStreetAssetScan/Program.cs
@@ -0,0 +1,313 @@
+using System.Buffers.Binary;
+using System.Text;
+using System.Text.RegularExpressions;
+using Microsoft.Xna.Framework.Content;
+
+namespace ReStreetAssetScan;
+
+// Explorer for FIFA Street's EA BIG archives, and the DualSense patcher. Only the patch commands
+// ("install"/"uninstall", "dualsense apply/revert") write to the game folder.
+// (no arguments), install, uninstall, status [ReStreet folder] player front end (EasyInstall.cs)
+// list <game folder> [--filter regex] every entry, nested BIGs included
+// extract <game folder> <output> [--filter regex] [--png] decoded copies of the matching entries
+// buttons <game folder> <output> controller-icon candidates as PNG + report
+internal static class Program
+{
+ internal sealed record Entry(string Name, int Offset, int Length, int TablePosition);
+ sealed record Asset(string Path, byte[] Data, int StoredLength);
+
+ // Where the controller art lives. The menus load the proxy art by path
+ // ("external/ion_sports07/platform/proxy/art/A" and so on); the tricks folder has an xenon
+ // and a ps3 copy of every skill-move picture.
+ static readonly (string Group, string Prefix)[] ButtonGroups =
+ {
+ ("Button prompts (menus and HUD)", "data/ui/external/ion_sports07/platform/proxy/art/"),
+ ("Skill-move pictures", "data/ui/imgassets/tricks/"),
+ ("Controller pictures", "data/ui/artassets/controllerimage/"),
+ ("Controller pictures", "data/ui/artassets/matchsettingicons/controller.big"),
+ };
+ const string ProxyArtReference = "external/ion_sports07/platform/proxy/art/";
+
+ internal static uint U(byte[] b, int p) => BinaryPrimitives.ReadUInt32BigEndian(b.AsSpan(p, 4));
+ internal static void Require(bool ok, string message) { if (!ok) throw new InvalidDataException(message); }
+
+ static int Main(string[] args)
+ {
+ try
+ {
+ // No arguments (double click) or install / uninstall / status: the player front end.
+ if (args.Length == 0 || args[0] is "install" or "uninstall" or "status") return EasyInstall.Run(args);
+ if (args.Length >= 3 && args[0] == "dualsense")
+ return DualSense.Run(args[1], args[2], args.Length > 3 && !args[3].StartsWith("--") ? args[3] : null,
+ Option(args, "--art"), Option(args, "--controller"));
+ if (args.Length < 2) return Usage();
+ string game = args[1];
+ Require(Directory.Exists(game), $"Folder not found: {game}");
+ string? filter = Option(args, "--filter");
+ var regex = filter is null ? null : new Regex(filter, RegexOptions.IgnoreCase);
+ switch (args[0])
+ {
+ case "list":
+ foreach (var asset in Walk(game, deep: true))
+ if (regex is null || regex.IsMatch(asset.Path))
+ Console.WriteLine($"{asset.StoredLength,10} {asset.Data.Length,10} {Kind(asset.Data),-9} {asset.Path}");
+ return 0;
+ case "extract":
+ Require(args.Length >= 3, "Missing output folder.");
+ int count = 0; bool png = args.Contains("--png");
+ foreach (var asset in Walk(game, deep: true))
+ if (regex is null || regex.IsMatch(asset.Path)) { Save(args[2], asset, png); count++; }
+ Console.WriteLine($"{count} entries written to {args[2]}");
+ return 0;
+ case "buttons":
+ Require(args.Length >= 3, "Missing output folder.");
+ return Buttons(game, args[2]);
+ default:
+ return Usage();
+ }
+ }
+ catch (Exception e) { Console.Error.WriteLine("error: " + e.Message); return 1; }
+ }
+
+ static int Usage()
+ {
+ Console.Error.WriteLine("ReStreetAssetScan [install|uninstall|status] [ReStreet folder]");
+ Console.Error.WriteLine("ReStreetAssetScan list <game folder> [--filter regex]");
+ Console.Error.WriteLine("ReStreetAssetScan extract <game folder> <output> [--filter regex] [--png]");
+ Console.Error.WriteLine("ReStreetAssetScan buttons <game folder> <output>");
+ Console.Error.WriteLine("ReStreetAssetScan dualsense preview <game folder> <output> --controller ps5 [--art folder]");
+ Console.Error.WriteLine("ReStreetAssetScan dualsense apply <game folder> --controller ps5 [--art folder]");
+ Console.Error.WriteLine("ReStreetAssetScan dualsense revert|status <game folder>");
+ return 2;
+ }
+
+ static string? Option(string[] args, string name)
+ {
+ int i = Array.IndexOf(args, name);
+ return i >= 0 && i + 1 < args.Length ? args[i + 1] : null;
+ }
+
+ // ---- Controller icons -------------------------------------------------------------------
+
+ static int Buttons(string game, string output)
+ {
+ Directory.CreateDirectory(output);
+ var textures = ButtonGroups.Select(g => g.Group).Distinct().ToDictionary(g => g, _ => new List<string>());
+ var references = new SortedDictionary<string, SortedSet<string>>(StringComparer.OrdinalIgnoreCase);
+ int saved = 0;
+ // The UI is in data0.big and data1.big; the other archives hold models, kits and audio.
+ foreach (var asset in Walk(game, deep: true, archive => Path.GetFileName(archive) is "data0.big" or "data1.big"))
+ {
+ string inner = asset.Path[(asset.Path.IndexOf('!') + 1)..];
+ var group = ButtonGroups.FirstOrDefault(g => inner.StartsWith(g.Prefix, StringComparison.OrdinalIgnoreCase));
+ if (group.Group is not null)
+ {
+ Save(output, asset, png: true); saved++;
+ foreach (var (suffix, image) in Textures.ToPng(asset.Data))
+ {
+ int w = BinaryPrimitives.ReadInt32BigEndian(image.AsSpan(16)), h = BinaryPrimitives.ReadInt32BigEndian(image.AsSpan(20));
+ textures[group.Group].Add($"| `{inner}{suffix}` | {Kind(asset.Data)} | {w}x{h} |");
+ }
+ }
+ else if (Kind(asset.Data) == "apt")
+ {
+ // Which screens draw which prompt: the Apt movie names the proxy art it imports.
+ string text = Encoding.Latin1.GetString(asset.Data);
+ for (int at = text.IndexOf(ProxyArtReference, StringComparison.OrdinalIgnoreCase); at >= 0;
+ at = text.IndexOf(ProxyArtReference, at + 1, StringComparison.OrdinalIgnoreCase))
+ {
+ int end = at + ProxyArtReference.Length;
+ while (end < text.Length && (char.IsLetterOrDigit(text[end]) || text[end] == '_')) end++;
+ string button = text[(at + ProxyArtReference.Length)..end];
+ if (button.Length == 0) continue;
+ string screen = inner.Contains(".big!") ? inner[..(inner.IndexOf(".big!") + 4)] : inner;
+ if (!references.TryGetValue(button.ToUpperInvariant(), out var screens)) references[button.ToUpperInvariant()] = screens = new(StringComparer.OrdinalIgnoreCase);
+ screens.Add(screen);
+ }
+ }
+ }
+
+ var report = new StringBuilder();
+ report.AppendLine("# Controller art in FIFA Street");
+ report.AppendLine();
+ report.AppendLine("Game folder: " + Path.GetFullPath(game));
+ report.AppendLine();
+ report.AppendLine("Every texture below was saved as a PNG next to its decoded entry in this folder.");
+ foreach (var (group, rows) in textures)
+ {
+ report.AppendLine(); report.AppendLine($"## {group} ({rows.Count})"); report.AppendLine();
+ report.AppendLine("| Entry | Format | Size |"); report.AppendLine("|---|---|---|");
+ foreach (string row in rows) report.AppendLine(row);
+ }
+ report.AppendLine(); report.AppendLine($"## Screens that use each button prompt ({references.Count} prompts)"); report.AppendLine();
+ report.AppendLine("| Prompt | Screens | Examples |"); report.AppendLine("|---|---|---|");
+ foreach (var (button, screens) in references)
+ report.AppendLine($"| {button} | {screens.Count} | {string.Join(", ", screens.Take(3).Select(s => $"`{s}`"))} |");
+ File.WriteAllText(Path.Combine(output, "REPORT.md"), report.ToString());
+ Console.WriteLine($"{saved} entries and {textures.Values.Sum(r => r.Count)} PNGs written to {output} (see REPORT.md)");
+ return 0;
+ }
+
+ // ---- Archive walking --------------------------------------------------------------------
+
+ static IEnumerable<Asset> Walk(string game, bool deep, Func<string, bool>? archives = null)
+ {
+ foreach (string file in Directory.EnumerateFiles(game, "*.big", SearchOption.AllDirectories).Order(StringComparer.OrdinalIgnoreCase))
+ {
+ if (archives is not null && !archives(file)) continue;
+ string relative = Path.GetRelativePath(game, file).Replace('\\', '/');
+ using var input = File.OpenRead(file);
+ var header = new byte[16];
+ if (input.Read(header) != 16 || !IsBig(header)) continue;
+ int tableEnd = (int)U(header, 12);
+ Require(tableEnd <= 8 * 1024 * 1024, $"Invalid directory size in {relative}");
+ Array.Resize(ref header, tableEnd); input.ReadExactly(header.AsSpan(16));
+ foreach (var e in Index(header, input.Length))
+ {
+ // Huge streamed payloads (audio, movies) are listed but not decoded.
+ if (e.Length > 64 * 1024 * 1024) { yield return new Asset($"{relative}!{e.Name}", Array.Empty<byte>(), e.Length); continue; }
+ var data = new byte[e.Length]; input.Position = e.Offset; input.ReadExactly(data);
+ foreach (var asset in Expand($"{relative}!{e.Name}", data, deep)) yield return asset;
+ }
+ }
+ }
+
+ static IEnumerable<Asset> Expand(string path, byte[] stored, bool deep)
+ {
+ byte[] data = stored;
+ try { data = Decode(stored); }
+ catch (Exception e) { Console.Error.WriteLine($"warning: {path}: {e.Message}"); }
+ yield return new Asset(path, data, stored.Length);
+ if (!deep || !IsBig(data)) yield break;
+ List<Entry> entries;
+ try { entries = Index(data, data.Length); }
+ catch (Exception e) { Console.Error.WriteLine($"warning: {path}: {e.Message}"); yield break; }
+ foreach (var e in entries)
+ foreach (var asset in Expand($"{path}!{e.Name}", data.AsSpan(e.Offset, e.Length).ToArray(), deep))
+ yield return asset;
+ }
+
+ internal static bool IsBig(byte[] b) => b.Length >= 16 && Encoding.ASCII.GetString(b, 0, 4) is "BIG4" or "BIGF";
+
+ internal static List<Entry> Index(byte[] b, long fileLength)
+ {
+ Require(IsBig(b), "Unsupported BIG archive.");
+ int count = (int)U(b, 8), end = (int)U(b, 12), p = 16;
+ Require(count <= 100000 && end <= b.Length, "Invalid BIG directory.");
+ var entries = new List<Entry>();
+ for (int i = 0; i < count; i++)
+ {
+ Require(p + 8 < end, "Truncated BIG directory.");
+ int offset = (int)U(b, p), length = (int)U(b, p + 4), zero = Array.IndexOf(b, (byte)0, p + 8, end - p - 8);
+ Require(zero >= 0 && (long)offset + length <= fileLength, "Invalid BIG entry.");
+ entries.Add(new(Encoding.UTF8.GetString(b, p + 8, zero - p - 8), offset, length, p)); p = zero + 1;
+ }
+ return entries;
+ }
+
+ // ---- Decoding (same formats as Installer/FifaStreetSetupTool/CreditPatch.cs) -------------
+
+ internal static byte[] Decode(byte[] b)
+ {
+ if (b.Length > 48 && Encoding.ASCII.GetString(b, 0, 8) is "chunklzx" or "chunkzip") b = DecodeChunk(b);
+ return DecodeRefPack(b);
+ }
+
+ // "chunklzx" holds Xbox LZX chunks (type 3), "chunkzip" raw deflate chunks (type 1); type 4 is stored.
+ static byte[] DecodeChunk(byte[] b)
+ {
+ Require(U(b, 8) == 2, "Unsupported chunk container version.");
+ int full = (int)U(b, 12), chunk = (int)U(b, 16), p = 40;
+ Require(full <= 256 * 1024 * 1024 && chunk is > 0 and <= 1024 * 1024, "Invalid chunklzx size.");
+ using var output = new MemoryStream(full);
+ while (output.Length < full)
+ {
+ p = (p + 7) / 16 * 16 + 8;
+ int n = (int)U(b, p), kind = (int)U(b, p + 4); p += 8;
+ Require(n > 0 && p + (long)n <= b.Length, "Truncated chunk.");
+ int target = Math.Min(chunk, full - (int)output.Length), end = p + n;
+ if (kind == 4) { Require(n == target, "Invalid raw chunk."); output.Write(b, p, n); p = end; continue; }
+ if (kind == 1)
+ {
+ long before = output.Length;
+ using (var deflate = new System.IO.Compression.DeflateStream(new MemoryStream(b, p, n, false), System.IO.Compression.CompressionMode.Decompress))
+ deflate.CopyTo(output);
+ Require(output.Length - before == target, "Invalid deflate chunk."); p = end; continue;
+ }
+ Require(kind == 3, "Unknown chunk type.");
+ var decoder = new LzxDecoder(17); int produced = 0;
+ while (p < end && produced < target)
+ {
+ int outSize = 32768, inSize;
+ if (b[p] == 255) { outSize = (b[p + 1] << 8) | b[p + 2]; inSize = (b[p + 3] << 8) | b[p + 4]; p += 5; }
+ else { inSize = (b[p] << 8) | b[p + 1]; p += 2; }
+ Require(inSize > 0 && p + inSize <= end && outSize > 0 && produced + outSize <= target, "Invalid LZX frame.");
+ using var input = new MemoryStream(b, p, inSize, false);
+ Require(decoder.Decompress(input, inSize, output, outSize) == 0, "LZX decompression failed.");
+ p += inSize; produced += outSize;
+ }
+ Require(produced == target, "Incomplete chunk."); p = end;
+ }
+ return output.ToArray();
+ }
+
+ static byte[] DecodeRefPack(byte[] b)
+ {
+ if (b.Length < 5 || b[0] != 0x10 || b[1] != 0xfb) return b;
+ int length = (b[2] << 16) | (b[3] << 8) | b[4], p = 5, at = 0;
+ Require(length <= 64 * 1024 * 1024, "Invalid RefPack size."); var result = new byte[length];
+ while (at < length && p < b.Length)
+ {
+ int c = b[p++], literals, copies = 0, distance = 0;
+ if (c < 0x80) { int d = b[p++]; literals = c & 3; copies = ((c & 0x1c) >> 2) + 3; distance = ((c & 0x60) << 3) + d + 1; }
+ else if (c < 0xc0) { int d = b[p++], e = b[p++]; literals = d >> 6; copies = (c & 0x3f) + 4; distance = ((d & 0x3f) << 8) + e + 1; }
+ else if (c < 0xe0) { int d = b[p++], e = b[p++], f = b[p++]; literals = c & 3; copies = ((c & 0x0c) << 6) + f + 5; distance = ((c & 0x10) << 12) + (d << 8) + e + 1; }
+ else if (c < 0xfc) literals = ((c & 0x1f) << 2) + 4;
+ else literals = c & 3;
+ Require(p + literals <= b.Length && at + literals + copies <= length, "Invalid RefPack data.");
+ Buffer.BlockCopy(b, p, result, at, literals); p += literals; at += literals;
+ Require(copies == 0 || distance <= at, "Invalid RefPack reference.");
+ for (int i = 0; i < copies; i++) { result[at] = result[at - distance]; at++; }
+ if (c >= 0xfc) break;
+ }
+ Require(at == length, "Incomplete RefPack data."); return result;
+ }
+
+ // ---- Output -----------------------------------------------------------------------------
+
+ static string Kind(byte[] b)
+ {
+ if (b.Length == 0) return "stream";
+ if (IsBig(b)) return "big";
+ string magic = Encoding.ASCII.GetString(b, 0, Math.Min(4, b.Length));
+ return magic switch
+ {
+ "SHPS" or "SHPX" => "fsh",
+ "DDS " => "dds",
+ "XPR2" => "xpr2",
+ "Apt " => "apt",
+ "\x89PNG" => "png",
+ "OTTO" => "otf",
+ "RIFF" => "riff",
+ "FWS" or "CWS" => "swf",
+ _ when b.Length >= 4 && BinaryPrimitives.ReadUInt32BigEndian(b) == 0x00010000 => "ttf",
+ _ when b.Length >= 3 && Encoding.ASCII.GetString(b, 0, 3) is "FWS" or "CWS" or "GFX" or "CFX" => "swf",
+ _ when b.Take(256).All(c => c is 9 or 10 or 13 or (>= 32 and < 127)) => "text",
+ _ => "bin:" + Convert.ToHexString(b, 0, Math.Min(4, b.Length)).ToLowerInvariant(),
+ };
+ }
+
+ static void Save(string output, Asset asset, bool png)
+ {
+ if (asset.Data.Length == 0) return;
+ string relative = string.Join('/', asset.Path.Split('!').Select(part => part.Replace(':', '_')));
+ string target = Path.Combine(output, relative.Replace('/', Path.DirectorySeparatorChar));
+ // A nested BIG is saved as "name.big.raw" so its folder of entries can sit next to it.
+ if (IsBig(asset.Data)) target += ".raw";
+ Directory.CreateDirectory(Path.GetDirectoryName(target)!);
+ File.WriteAllBytes(target, asset.Data);
+ if (!png) return;
+ try { foreach (var (suffix, image) in Textures.ToPng(asset.Data)) File.WriteAllBytes(target + suffix + ".png", image); }
+ catch (Exception e) { Console.Error.WriteLine($"warning: {asset.Path}: PNG conversion failed: {e.Message}"); }
+ }
+}
diff --git a/Tools/ReStreetAssetScan/README.md b/Tools/ReStreetAssetScan/README.md
new file mode 100644
index 0000000..a651ddf
--- /dev/null
+++ b/Tools/ReStreetAssetScan/README.md
@@ -0,0 +1,69 @@
+# ReStreetAssetScan
+
+Read-only explorer for FIFA Street's EA BIG archives (`data0.big` … `data7.big` and the `.big` files under `data/`). It opens nested BIGs, decodes `chunklzx` (Xbox LZX), `chunkzip` (deflate) and RefPack entries, and converts DDS and Xbox 360 XPR2 textures to PNG. It never writes to the game folder.
+
+```bash
+dotnet build -c Release Tools/ReStreetAssetScan
+```
+
+```bash
+ReStreetAssetScan list <game folder> [--filter regex]
+ReStreetAssetScan extract <game folder> <output> [--filter regex] [--png]
+ReStreetAssetScan buttons <game folder> <output>
+```
+
+`<game folder>` is the ReStreet `Game` folder (or the old `GameData`). Entry paths use `!` between archive levels, for example `data0.big!data/ui/external/ion_sports07/platform/proxy/art/a.big!2`.
+
+`buttons` saves every controller texture as PNG and writes `REPORT.md` with:
+
+- **Button prompts**: `data/ui/external/ion_sports07/platform/proxy/art/*.big` in `data0.big` (A, B, X, Y, LB, RB, LT, RT, LS/RS directions, D-pad, START, BACK, the Guide button) and `controllers.big` / `tricks.big` in `data1.big`. Each menu imports these by path, so one texture changes every screen that shows that button.
+- **Skill-move pictures**: `data/ui/imgassets/tricks/xenon/` and `.../tricks/ps3/`. The game ships both sets; the PS3 one already uses R, R1, L1 and R3.
+- **Controller pictures**: `controller_xbox360.big` and `controller_ps3.big`.
+- Which screens use each prompt.
+
+Keep the output out of Git: it is game data (`private/` is ignored).
+
+## DualSense button art
+
+```bash
+ReStreetAssetScan dualsense preview <game folder> <output> --controller ps5
+ReStreetAssetScan dualsense apply <game folder> --controller ps5
+ReStreetAssetScan dualsense revert <game folder>
+ReStreetAssetScan dualsense status <game folder>
+```
+
+`--controller` says which PlayStation pad the art is for and is required by `preview` and `apply`. It is stored as one byte (`ps5` = `0x05`, the DualSense, the only art so far; `ps4` = `0x04` is reserved for the DualShock 4 and refused until its art exists). `apply` writes it into the backups (`RSD2` + that byte) and `status` reads it back.
+
+Close the game first. `preview` writes before/after PNGs and changes nothing. `apply` patches `data0.big`, `data1.big` and their `.bh` indexes:
+
+- **Button prompts** (35 textures): the game's own texture keeps its outline and shading; the Xbox symbol inside the black face is replaced with a glyph from `DualSense/`: A ✕, B ○, X □, Y △, LB/RB L1/R1, LT/RT L2/R2, LS/RS L/R, L3/R3, START Options, BACK Create, Guide PS.
+- **Skill-move list**: the `tricks/xenon/` pictures point at the PS3 set the game already ships.
+- **In-match skill hints** (`proxy/art/tricks.big`): rebuilt from the PS3 pictures, keeping the HUD's brighter arrows.
+- **Select Sides controller**: a white DualSense drawn by `make_glyphs.py` replaces the Xbox 360 pad in both controller sets in `data1.big`:
+ - `data/ui/game/components/fifasideselector.big`, used by the offline Select Sides screen: texture 33 (pad), 30 (the strip the game tints with each player's colour) and 8 (the empty-slot silhouette) become `sideselector*.png`.
+ - `proxy/art/controllers.big`: texture 5 (pad) and 2 (strip) become `controller*.png`.
+
+ The strip sits along the bottom of the pad's black centre, where the game draws it.
+
+Changed entries are appended to the archive, as the installer's credit patch does. The original directory, index and length are saved to `<archive>.dualsense-backup` first; `revert` restores the files byte for byte. Revert before running a ReStreet update or repair, and apply again afterwards.
+
+### Your own controller picture
+
+1. If the picture's "transparent" background is a checkerboard saved into the pixels, cut it out:
+ `python DualSense/cutout.py <picture.png> private/dualsense-cutout.png`
+2. Build the Select Sides textures from it (front view, cropped tight; strip style `pill`, `accents` or `none`):
+ `python DualSense/pad_from_image.py private/dualsense-cutout.png private/dualsense-art pill`
+3. Patch with that folder; files missing from it come from `DualSense/`:
+ `ReStreetAssetScan dualsense apply <game folder> --controller ps5 --art private/dualsense-art`
+
+Keep pictures you did not make yourself, and what is built from them, in `private/` (not in Git).
+
+### Controls screens (call-out lines)
+
+The loading screens, the Game Manual and the controller settings are switched to their PlayStation layout, whose lines point at the game's DualShock 3 photo. To show a DualSense there instead, give a picture **shot from above like that photo** (L2/R2 visible behind L1/R1), cut out, plus its button centres:
+
+`python DualSense/controls_from_image.py private/dualsense-controles-cutout.png private/dualsense-controles-points.json private/dualsense-art`
+
+It fits the picture on the line ends (`controls.png`, 512×256) and reuses that placement ×1.45 for the settings copy (`controls_large.png`, 1024×512, whose visible area clips the grip tips). Without these two files the screens keep the DualShock 3 photo.
+
+The glyphs are original art. Edit the PNGs or regenerate them with `python DualSense/make_glyphs.py`; the patcher scales each one into the button face.
diff --git a/Tools/ReStreetAssetScan/RELATORIO-DUALSENSE.md b/Tools/ReStreetAssetScan/RELATORIO-DUALSENSE.md
new file mode 100644
index 0000000..90cc39c
--- /dev/null
+++ b/Tools/ReStreetAssetScan/RELATORIO-DUALSENSE.md
@@ -0,0 +1,218 @@
+# Mod DualSense para o ReStreet: relatório final
+
+Versão final, 21/10/2026. Aplicado e confirmado no jogo numa instalação do ReStreet 2.0.
+
+## 1. Resumo
+
+O ReStreet é a versão de Xbox 360 do FIFA Street (2012) recompilada pro PC, então toda a arte de controle é de Xbox. O mod troca essa arte pela do controle de PlayStation 5 (DualSense). Ele só altera **dados do jogo**: `data0.big`, `data1.big` e os índices `.bh` deles. O executável, o runtime e o launcher não mudam.
+
+| Área | O que muda no jogo | Arquivo | Como | No jogo |
+|---|---|---|---|---|
+| Prompts de botão (menus e HUD) | A/B/X/Y → ✕/○/□/△, LB/RB → L1/R1, LT/RT → L2/R2, LS/RS → L/R, L3/R3, START → Options, BACK → Create, Guide → PS | `data0.big` | 35 texturas: o símbolo é redesenhado e o contorno original fica | Confirmado |
+| Lista de skill moves | RS/RB/LB → R/R1/L1/R3 | `data1.big` | 38 entradas redirecionadas para o conjunto PS3 que o jogo já tem | Aplicado |
+| Dicas de skill move na partida | Mesma troca, com o verde do HUD | `data1.big` | 37 texturas montadas a partir das imagens de PS3 | Aplicado |
+| Seleção de lados | Controle de 360 → DualSense branco, com a barra de cor do jogador e a silhueta dos slots vazios | `data1.big` | 5 texturas em 2 arquivos | Confirmado |
+| Telas de controles (loading ×2, Manual do Jogo, configurações) | Layout PlayStation, com as linhas de legenda apontando pros botões do DualSense | `data1.big` | 1 constante trocada em 5 telas + 4 fotos trocadas | Confirmado |
+
+## 2. Como instalar
+
+Tudo fica numa pasta só, `ReStreet-DualSense` (no projeto, `private/ReStreet-DualSense`, ~76 MB), gerada por `pack.ps1`:
+
+```
+ReStreet-DualSense/
+ Instalar DualSense.cmd dois cliques para aplicar
+ Remover DualSense.cmd dois cliques para voltar ao original
+ ReStreetDualSense.exe o patcher (exe único, já traz o .NET; ~67 MB)
+ LEIA-ME.txt instruções curtas
+ DualSense/ a arte que o instalador aplica (22 PNG)
+ Relatorio/ este relatório
+ Codigo-fonte/ o código da ferramenta (compila sozinho: dotnet build)
+ Imagens-originais/ as imagens de DualSense usadas, os recortes e os centros dos botões
+ Referencias/ folhas de referência: templates, antes/depois, simulações
+```
+
+Pra gerar a pasta de novo:
+
+```bash
+powershell -ExecutionPolicy Bypass -File Tools/ReStreetAssetScan/pack.ps1 -Art private/dualsense-art -Output private/ReStreet-DualSense -Originals "private/dualsense*.png,private/dualsense-controles-points.json" -References "private/dualsense-reference/*.png,private/button-art/_sheets/*.png"
+```
+
+1. **Feche o FIFA Street.** O launcher pode ficar aberto. Se o jogo estiver rodando, o instalador avisa e não mexe em nada.
+2. Dê dois cliques em **Instalar DualSense.cmd**. A instalação do ReStreet é encontrada sozinha:
+ 1. pela pasta arrastada pra cima do `.cmd`, se houver;
+ 2. pela pasta onde o exe estiver, se ele for colocado dentro do ReStreet;
+ 3. pelo atalho `ReStreet.lnk` da Área de Trabalho ou do Menu Iniciar;
+ 4. por uma busca rasa nos discos.
+
+ Em todos os casos, o `settings.json` do launcher diz qual pasta `Game` usar. Se houver mais de uma instalação e o atalho não resolver, ele pergunta qual.
+3. **Antes de atualizar ou reparar o ReStreet:** rode **Remover DualSense.cmd**, atualize pelo launcher e instale de novo.
+
+Pelo terminal: `ReStreetDualSense.exe install|uninstall|status [pasta do ReStreet]`, ou, no modo avançado, `dualsense apply|revert|status|preview <pasta Game> --controller ps5 [--art pasta]`.
+
+## 3. Como os dados do jogo estão organizados
+
+**BIG** (EA):
+- cabeçalho `BIG4`/`BIGF` com número de entradas e tamanho do diretório, em big-endian;
+- uma lista de entradas com offset, tamanho e nome.
+
+Cada `.big` tem um índice `.bh` (`ViV4`) com registros de 20 bytes. Offset e tamanho aparecem nos dois lugares, então os dois são atualizados juntos.
+
+Formatos dentro dos BIG:
+- **`chunklzx`:** LZX do Xbox, da mesma família do CAB da Microsoft, em blocos de 256 KB com frames de 32 KB e janela de 2¹⁷. Cada tela de UI é um **BIG interno** nesse formato, com o filme Apt, as geometrias e as texturas.
+- **RefPack** (`10 FB`): o LZ77 da EA, sem codificação de entropia. É usado nas texturas e em alguns filmes dentro dos BIG internos.
+- **`chunkzip`:** os mesmos blocos, com deflate. É usado nos DDS de skill move.
+
+**Texturas XPR2** (Xbox 360): o cabeçalho traz o *fetch constant* da GPU Xenos (formato, endianness, tiling e dimensões). Os dados vêm em DXT5, com bytes trocados a cada 16 bits e layout *tiled* (o endereço é calculado por `XGAddress2DTiledOffset`).
+
+**Apt**, o formato de UI da EA derivado do Flash:
+- `0` é o filme, com bytecode parecido com o ActionScript 2;
+- `1` é a **tabela de constantes**, com as strings usadas pelo código (nomes de clipes, caminhos, plataformas).
+
+## 4. O que cada parte faz e por quê
+
+### 4.1 Prompts de botão (`data0.big`, `…/platform/proxy/art/*.big`)
+
+**Achado.** As telas importam os botões por caminho (`external/ion_sports07/platform/proxy/art/A` e assim por diante), e cada botão é uma textura só, compartilhada pelo jogo inteiro: o "A" é usado em 107 telas.
+
+**Como.**
+1. A textura é decodificada: tiling desfeito, bytes reordenados, DXT5 descomprimido.
+2. Um *flood fill* a partir das bordas, que só passa por pixels não escuros, separa o lado de fora (contorno claro e transparência) da face preta do botão. A região fechada com mais pixels claros é a face com o símbolo do Xbox.
+3. A face é repintada com o preto médio original e recebe o glifo do PlayStation, escalado, centralizado, com supersampling 4×4 e uma borda preta de 1 texel.
+4. A textura volta pro mesmo formato, ordem de bytes, tiling e lugar.
+
+O botão Guide é exceção: o logo encosta no contorno e não forma uma face fechada, então a face é o disco ajustado à área escura.
+
+**Por quê.** Manter a textura original e trocar só o símbolo preserva o contorno, o sombreado e as bordas que a geometria de cada quadro espera. Os glifos (`DualSense/*.png`, gerados por `make_glyphs.py`) são arte original.
+
+**Encoder DXT5.** As duas cores-base de cada bloco 4×4 partem do texel mais escuro e do mais claro e são refinadas por **mínimos quadrados**: os índices ficam fixos e resolve-se o sistema 2×2 das cores, em 4 iterações, ficando o melhor resultado. O alfa usa o modo de 8 níveis. Sem esse refinamento, as cores pequenas sumiam e o branco ficava com blocos.
+
+### 4.2 Lista de skill moves (`data1.big`, `data/ui/imgassets/tricks/`)
+
+O jogo traz as imagens em `xenon/` e em `ps3/`, com os mesmos nomes. As 38 entradas de `xenon/` passam a apontar, no diretório e no `.bh`, para os dados de `ps3/`. Nenhum byte de imagem é gravado: é a arte oficial do próprio jogo, e a troca custa 8 bytes por entrada.
+
+### 4.3 Dicas de skill move na partida (`proxy/art/tricks.big`)
+
+Esse conjunto só existe na versão Xbox. Comparando a transparência, a textura `2k` corresponde a `trick_(38+k)` (36 de 37 batem exatamente; a outra é idêntica a uma vizinha).
+
+A troca é uma *transferência de diferença*: `saída = HUD_xbox + (lista_PS3 − lista_xbox)`, com limite em 0–255. As setas são iguais nas duas listas, então ali a diferença é zero e o verde do HUD fica intacto. Onde os rótulos mudam, a diferença carrega o rótulo do PlayStation.
+
+### 4.4 Seleção de lados
+
+**Achado.** A tela offline usa `data/ui/game/components/fifasideselector.big`:
+- **33:** o controle (256×128);
+- **30:** uma faixa branca que o jogo pinta com a cor de cada jogador;
+- **8:** a silhueta dos slots vazios.
+
+O mesmo arquivo traz um conjunto PS3 que o Xbox não usa. O `proxy/art/controllers.big` tem uma cópia menor, provavelmente a da versão online; as duas são trocadas.
+
+**Como.**
+- `cutout.py` remove o xadrez de "transparência falsa" que vinha salvo nos pixels da imagem, com um flood fill pelas bordas, por pixels claros e neutros, parando no contorno do controle.
+- `pad_from_image.py` encaixa a imagem sem distorcer onde ficava o 360, com alfa pré-multiplicado e supersampling (sem halo), e gera a silhueta a partir da transparência, no cinza translúcido original.
+- **A faixa de cor** tem posição fixa em relação ao controle, então foi **medida nos prints do jogo**. A medição foi validada reproduzindo a tela com a arte original do 360. Como a faixa só aparece no quarto de baixo do quadro, ela virou uma barra de jogador no vão entre as alças (opção B).
+
+### 4.5 Telas de controles: o layout PlayStation
+
+| Tela (`data1.big`) | Onde aparece | Como pega a foto |
+|---|---|---|
+| `screens/settings/controllersetup.big` | Configurações > Controle | Carrega `controller_xbox360.swf` / `controller_PS3.swf` pelo caminho |
+| `screens/settings/controllerconfiguration.big` | Configuração de botões | Idem |
+| `overlays/overlay_79.big` | Loading ("CONTROLES" + "DICAS") | Embute as duas fotos (47 = 360, 74 = DualShock 3) |
+| `overlays/overlay_87.big` | Loading, outra variante | Embute as duas (50 = 360, 80 = DualShock 3) |
+| `screens/misc/ingamemanual.big` | Pausa > Manual do Jogo | Embute as duas (61 = 360, 17 = DualShock 3) |
+
+**Achado.** O bytecode escolhe o layout pela plataforma. Decompilado de forma aproximada, em `controllersetup`:
+
+```
+linhas = PLATFORM == "PS3" ? mcLinesPS3 : mcLines
+se PS3: imagem = controller_PS3.swf, escala 75%
+senão: remove mcLineLayer; imagem = controller_xbox360.swf
+```
+
+No Xbox, `PLATFORM` vale `XENON`.
+
+**Como.** Na tabela de constantes de cada tela, a entrada `"PS3"` passa a apontar pra uma string `"XENON"` acrescentada no fim. O teste dá verdadeiro e **só essas telas** seguem o ramo PlayStation.
+
+**Por quê.** As linhas do Xbox apontam pro layout do 360 (analógico esquerdo em cima, direcional embaixo), o contrário do DualSense. O ramo PS3 já traz linhas pro layout PlayStation, que é o do DualSense. Trocar uma constante evita mexer no bytecode e nos offsets de desvio.
+
+### 4.6 O DualSense no lugar da foto do DualShock 3
+
+**Achado.**
+- As três cópias embutidas são a mesma textura de 512×256, e o jogo desenha os texels (0,0)–(400,250).
+- O `controller_ps3.big` é a mesma foto ampliada 1,45× (registro pela transparência, diferença média de 1,5/255), em 1024×512, com área visível até (548,297).
+- As linhas terminam em 11 botões da foto: L2, L1, R2, R1, direcional, △□○✕, L3 e R3.
+
+**A imagem precisa ter o ângulo da foto do DS3**, de cima e na diagonal, com os gatilhos aparecendo atrás dos bumpers e os analógicos no pé da imagem. Numa imagem frontal, o melhor encaixe errava 22–23 texels em média: os ombros ficavam 47–69 texels no ar. Com a imagem no ângulo certo:
+
+| Botões | Desvio |
+|---|---|
+| Direcional, △□○✕ | 3–10 texels |
+| L3, R3 | 9–10 texels |
+| L2, R2 | 15 texels |
+| L1, R1 | 19 texels (o ponto cai no topo do bloco do gatilho) |
+| **Média** | **9 texels** |
+
+**Como** (`controls_from_image.py`):
+1. Escala praticamente uniforme (até 8% de diferença entre os eixos) e posição por mínimos quadrados ponderados sobre os 11 pontos, com peso 0,5 nos ombros, sempre dentro da área visível.
+2. Na versão grande, encaixar o controle inteiro em y ≤ 297 faria as linhas errarem 26 texels. Então ela usa o mesmo encaixe da pequena, convertido por ×1,45, e o jogo corta as pontas das alças. Entre "linhas certas" e "alças inteiras", ficaram as linhas certas.
+3. O patcher grava as 4 texturas na mesma remontagem que troca a constante. Sem os arquivos `controls*.png`, as telas ficam com a foto do DS3.
+
+## 5. Como o patch é gravado e desfeito
+
+**Gravação.** As entradas alteradas são **acrescentadas no fim** do `.big`, sem compressão, como o patch de créditos do instalador do ReStreet já faz. O diretório do BIG e o `.bh` passam a apontar pra elas. Os BIG internos são remontados com as entradas trocadas e as demais intactas.
+
+**Perfil do controle.** O `apply` exige `--controller`, gravado como **um byte**:
+- `0x05` = PS5 DualSense: a arte que existe hoje, e o que o `Instalar DualSense.cmd` usa;
+- `0x04` = PS4 DualShock 4: reconhecido, mas recusado até a arte existir.
+
+O byte fica no backup (formato `RSD2`: `"RSD2"`, o byte, e depois o conteúdo do backup). O `status` lê esse byte e o `revert` também aceita o formato antigo (`RSDS`).
+
+**Segurança.**
+- Antes de escrever, o diretório, o `.bh` e o tamanho originais vão para `<arquivo>.dualsense-backup`. O `revert` regrava os dois e corta o arquivo no tamanho original.
+- Entradas e índices são conferidos antes de gravar. Se o formato do arquivo não for o esperado (uma versão nova do jogo, por exemplo), o patch para com erro em vez de gravar errado.
+- O jogo precisa estar fechado: o instalador verifica isso, e os arquivos são abertos com acesso exclusivo.
+
+## 6. Testes feitos
+
+- **Ida e volta:** `apply` e depois `revert` numa cópia dos quatro arquivos, repetidos a cada mudança. Os arquivos voltam **idênticos byte a byte** (SHA-256). O mesmo vale na instalação real, conferido antes e depois de um update do ReStreet; o update não altera `data0`/`data1`.
+- **Leitura de volta:** depois do `apply`, todas as entradas alteradas são lidas e decodificadas pela própria ferramenta (texturas, constantes e redirecionamentos).
+- **Flag do controle:** sem a flag, com `ps4` e com um valor desconhecido, o patcher recusa sem tocar em nada. Com `ps5`, o backup começa com `RSD2 05` e o `status` confirma.
+- **Pacote:** a detecção automática acha a pasta `Game` da instalação 2.0 pelo atalho do launcher, mesmo com uma instalação antiga no mesmo disco. Uma pasta errada é recusada, e com o jogo aberto o instalador se recusa a mexer nos arquivos. O exe do pacote acha toda a arte da própria pasta (`preview`: 35 prompts, 38 + 37 skill moves, seleção de lados e as 4 fotos).
+- **No jogo** (pelo usuário): prompts, seleção de lados, loading e Manual do Jogo.
+- **Ainda não feito:** rodar o `install` e o `uninstall` pelo pacote com o jogo fechado. Eles chamam as mesmas operações já testadas, mas esse caminho exato ainda não rodou.
+
+## 7. Caminho descartado: a pasta Mods
+
+O runtime do ReStreet lê `Mods/<arquivo>@<offset>.bin` e entrega esses bytes no lugar dos originais, sem alterar os arquivos. Só que ele **não deixa o arquivo crescer**, e as entradas do mod, sem compressão, ficam 6–10× maiores que o espaço original.
+
+Cheguei a escrever encoders LZX e RefPack que ficavam só 2,9% maiores que os da EA. Mesmo assim, ainda faltava encaixar as entradas nos espaços livres, e o `data0.big` quase não tem sobra. A instalação 2.0 também não tem mais a pasta `Mods`. Ficou decidido usar a substituição direta, mais simples e já validada, e esse código foi removido.
+
+## 8. Ferramenta
+
+Pasta `Tools/ReStreetAssetScan` (ainda não commitada):
+
+| Arquivo | Papel |
+|---|---|
+| `Program.cs` | Leitura dos BIG; `list`, `extract`, `buttons` |
+| `EasyInstall.cs` | Modo jogador: menu, `install`/`uninstall`/`status`, detecção da instalação, checagem do jogo aberto |
+| `DualSense.cs` | O patch: `preview`/`apply`/`revert`/`status`, `--controller`, `--art` |
+| `Textures.cs` | XPR2/DDS ↔ RGBA (tiling Xenos, DXT1/3/5, encoder DXT5), PNG |
+| `DualSense/make_glyphs.py` | Glifos (arte original) e um DualSense desenhado, usado quando não há imagem |
+| `DualSense/cutout.py` | Remove o xadrez de "transparência falsa" |
+| `DualSense/pad_from_image.py` | Texturas da seleção de lados a partir de uma imagem |
+| `DualSense/controls_from_image.py` | Fotos das telas de controles a partir de uma imagem e dos centros dos botões |
+| `pack.ps1` | Monta o pacote (exe único + arte + `.cmd` + LEIA-ME) |
+
+As imagens de DualSense usadas e tudo o que foi gerado delas ficam em `private/`, que não vai pro Git:
+- `dualsense.png`, `dualsense-controles.png` e os recortes;
+- `dualsense-controles-points.json`;
+- `dualsense-art/`;
+- o pacote `ReStreet-DualSense/`.
+
+## 9. Limites e pendências
+
+- **Imagens da Sony.** As fotos do DualSense parecem renders oficiais da Sony. Pra uso próprio, tudo bem. Pra distribuir o pacote a outras pessoas, o seguro é montar o pacote só com a arte original (`pack.ps1` sem `-Art`). Aí a seleção de lados usa o DualSense desenhado e as telas de controles ficam com o DS3, até existir uma arte de DualSense própria.
+- **L1/R1 nas telas de controles** ficam ~19 texels acima do bumper. Corrigir exige editar o posicionamento das linhas no filme Apt.
+- **Alças cortadas** nas telas de configuração de controle (versão grande da foto), pelo motivo da seção 4.6.
+- **Ramo PS3 das telas de controles.** Ele também chama funções de PlayStation (por exemplo `GetAdvanceButton`). Nada de errado apareceu no jogo, mas um comportamento estranho nessas telas viria daí, e o `revert` desfaz.
+- **DualShock 4 (PS4).** O byte `0x04` já está reservado. Falta a arte: glifos (Options/Share no lugar de Options/Create, touchpad), a imagem da seleção de lados e a imagem das telas de controles.
+- **Updates do ReStreet.** Sempre remover antes de atualizar e instalar de novo depois. Se um update mudar o `data1.big` com o mod aplicado, o `revert` recusa (o arquivo não bate com o backup) em vez de estragar.
diff --git a/Tools/ReStreetAssetScan/ReStreetAssetScan.csproj b/Tools/ReStreetAssetScan/ReStreetAssetScan.csproj
new file mode 100644
index 0000000..a924e43
--- /dev/null
+++ b/Tools/ReStreetAssetScan/ReStreetAssetScan.csproj
@@ -0,0 +1,16 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net8.0</TargetFramework>
+ <RollForward>Major</RollForward>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ <AssemblyName>ReStreetAssetScan</AssemblyName>
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="..\..\Installer\FifaStreetSetupTool\ThirdParty\LzxDecoder.cs" Link="ThirdParty\LzxDecoder.cs" />
+ <None Include="DualSense\*.png" CopyToOutputDirectory="PreserveNewest" />
+ </ItemGroup>
+
+</Project>
diff --git a/Tools/ReStreetAssetScan/Textures.cs b/Tools/ReStreetAssetScan/Textures.cs
new file mode 100644
index 0000000..7ad6488
--- /dev/null
+++ b/Tools/ReStreetAssetScan/Textures.cs
@@ -0,0 +1,407 @@
+using System.Buffers.Binary;
+using System.IO.Compression;
+using System.Text;
+
+namespace ReStreetAssetScan;
+
+// Converts the game's textures to PNG for viewing: plain DDS (the imgassets folders) and
+// Xbox 360 XPR2 packages (the textures inside each UI .big), which are big-endian and tiled.
+internal static class Textures
+{
+ // Returns one PNG per texture found, or nothing when the data is not a supported texture.
+ internal static IEnumerable<(string Name, byte[] Png)> ToPng(byte[] b)
+ {
+ if (b.Length >= 128 && Encoding.ASCII.GetString(b, 0, 4) == "DDS ")
+ {
+ var png = FromDds(b);
+ if (png is not null) yield return ("", png);
+ }
+ else if (b.Length >= 16 && Encoding.ASCII.GetString(b, 0, 4) == "XPR2")
+ {
+ foreach (var item in FromXpr2(b)) yield return item;
+ }
+ }
+
+ // ---- DDS ----------------------------------------------------------------------------------
+
+ static byte[]? FromDds(byte[] b)
+ {
+ var image = DecodeDds(b);
+ return image is null ? null : Png(image.Value.Rgba, image.Value.Width, image.Value.Height);
+ }
+
+ internal static (byte[] Rgba, int Width, int Height)? DecodeDds(byte[] b)
+ {
+ if (b.Length < 128 || Encoding.ASCII.GetString(b, 0, 4) != "DDS ") return null;
+ int height = BinaryPrimitives.ReadInt32LittleEndian(b.AsSpan(12)), width = BinaryPrimitives.ReadInt32LittleEndian(b.AsSpan(16));
+ int pfFlags = BinaryPrimitives.ReadInt32LittleEndian(b.AsSpan(80));
+ string fourcc = Encoding.ASCII.GetString(b, 84, 4);
+ if (width is <= 0 or > 8192 || height is <= 0 or > 8192) return null;
+ var data = b.AsSpan(128);
+ byte[]? rgba = (pfFlags & 4) != 0
+ ? fourcc switch { "DXT1" => Dxt(data, width, height, 1), "DXT3" => Dxt(data, width, height, 3), "DXT5" => Dxt(data, width, height, 5), _ => null }
+ : BinaryPrimitives.ReadInt32LittleEndian(b.AsSpan(88)) == 32 && data.Length >= width * height * 4 ? Bgra(data, width, height) : null;
+ return rgba is null ? null : (rgba, width, height);
+ }
+
+ static byte[] Bgra(ReadOnlySpan<byte> s, int width, int height)
+ {
+ var rgba = new byte[width * height * 4];
+ for (int i = 0; i < width * height; i++)
+ { rgba[i * 4] = s[i * 4 + 2]; rgba[i * 4 + 1] = s[i * 4 + 1]; rgba[i * 4 + 2] = s[i * 4]; rgba[i * 4 + 3] = s[i * 4 + 3]; }
+ return rgba;
+ }
+
+ // ---- XPR2 ---------------------------------------------------------------------------------
+
+ static IEnumerable<(string, byte[])> FromXpr2(byte[] b)
+ {
+ uint headerSize = BE(b, 4), count = BE(b, 12);
+ long dataStart = headerSize + 12;
+ for (int i = 0; i < count && 16 + i * 16 + 16 <= b.Length; i++)
+ {
+ int r = 16 + i * 16;
+ if (Encoding.ASCII.GetString(b, r, 4) != "TX2D") continue;
+ int header = (int)BE(b, r + 4) + 12, nameAt = (int)BE(b, r + 12) + 12;
+ string name = nameAt < b.Length ? ReadName(b, nameAt) : $"tex{i}";
+ byte[]? png = null;
+ try
+ {
+ var texture = XenosTexture.Parse(b, header + 28, dataStart);
+ if (texture is not null) png = Png(texture.Read(b), texture.Width, texture.Height);
+ }
+ catch (Exception) { }
+ if (png is not null) yield return (count > 1 ? "_" + Safe(name) : "", png);
+ }
+ }
+
+ // The first TX2D texture of an XPR2 package (every UI texture in the game has exactly one).
+ internal static XenosTexture? FirstXpr2Texture(byte[] b)
+ {
+ if (b.Length < 32 || Encoding.ASCII.GetString(b, 0, 4) != "XPR2" || Encoding.ASCII.GetString(b, 16, 4) != "TX2D") return null;
+ return XenosTexture.Parse(b, (int)BE(b, 20) + 12 + 28, BE(b, 4) + 12);
+ }
+
+ static string ReadName(byte[] b, int at) { int end = Array.IndexOf(b, (byte)0, at); return Encoding.ASCII.GetString(b, at, (end < 0 ? b.Length : end) - at); }
+ static string Safe(string s) => string.Concat(s.Select(c => char.IsLetterOrDigit(c) || c is '_' or '-' ? c : '_'));
+
+ // A GPU texture fetch constant (6 dwords) describes the base mip level.
+ internal sealed record XenosTexture(long Offset, int Width, int Height, int Format, int Endian, bool Tiled, int BlocksW, int BlocksH, int AlignedW, int Bytes)
+ {
+ internal static XenosTexture? Parse(byte[] b, int fetch, long dataStart)
+ {
+ uint d0 = BE(b, fetch), d1 = BE(b, fetch + 4), d2 = BE(b, fetch + 8);
+ int format = (int)(d1 & 63);
+ int width = (int)(d2 & 0x1FFF) + 1, height = (int)((d2 >> 13) & 0x1FFF) + 1;
+ (int blockSize, int bytes) = format switch { 0x12 => (4, 8), 0x13 or 0x14 => (4, 16), 0x06 => (1, 4), 0x02 => (1, 1), _ => (0, 0) };
+ if (blockSize == 0) return null;
+ int blocksW = (width + blockSize - 1) / blockSize, blocksH = (height + blockSize - 1) / blockSize;
+ var texture = new XenosTexture(dataStart + ((d1 >> 12) << 12), width, height, format, (int)((d1 >> 6) & 3), (d0 >> 31) != 0,
+ blocksW, blocksH, (blocksW + 31) & ~31, bytes);
+ return texture.Block(blocksW - 1, blocksH - 1) + bytes <= b.Length ? texture : null;
+ }
+
+ long Block(int x, int y) => Offset + (Tiled ? TiledOffset(x, y, AlignedW, Bytes) : (long)y * AlignedW + x) * Bytes;
+
+ // Untiles into a linear block array, undoes the GPU byte order and decodes to RGBA.
+ internal byte[] Read(byte[] b)
+ {
+ var linear = new byte[BlocksW * BlocksH * Bytes];
+ for (int y = 0; y < BlocksH; y++)
+ for (int x = 0; x < BlocksW; x++)
+ Buffer.BlockCopy(b, (int)Block(x, y), linear, (y * BlocksW + x) * Bytes, Bytes);
+ Swap(linear, Endian);
+ return Format switch
+ {
+ 0x12 => Dxt(linear, Width, Height, 1, BlocksW),
+ 0x13 => Dxt(linear, Width, Height, 3, BlocksW),
+ 0x14 => Dxt(linear, Width, Height, 5, BlocksW),
+ 0x06 => Argb(linear, Width, Height),
+ _ => Gray(linear, Width, Height),
+ };
+ }
+
+ // Encodes RGBA back into the same place, format and byte order (DXT5 only, the format of all UI art).
+ internal void Write(byte[] b, byte[] rgba)
+ {
+ if (Format != 0x14) throw new NotSupportedException($"Writing texture format 0x{Format:x} is not supported.");
+ byte[] linear = EncodeDxt5(rgba, Width, Height);
+ Swap(linear, Endian);
+ for (int y = 0; y < BlocksH; y++)
+ for (int x = 0; x < BlocksW; x++)
+ Buffer.BlockCopy(linear, (y * BlocksW + x) * Bytes, b, (int)Block(x, y), Bytes);
+ }
+ }
+
+ // XGAddress2DTiledOffset: element index of block (x, y) in a tiled Xenos surface.
+ static long TiledOffset(int x, int y, int alignedWidth, int bytesPerBlock)
+ {
+ int logBpp = (bytesPerBlock >> 2) + ((bytesPerBlock >> 1) >> (bytesPerBlock >> 2));
+ int macro = ((x >> 5) + (y >> 5) * (alignedWidth >> 5)) << (logBpp + 7);
+ int micro = ((x & 7) + ((y & 6) << 2)) << logBpp;
+ int offset = macro + ((micro & ~15) << 1) + (micro & 15) + ((y & 8) << (3 + logBpp)) + ((y & 1) << 4);
+ return (((offset & ~511) << 3) + ((offset & 448) << 2) + (offset & 63) + ((y & 16) << 7) + (((((y & 8) >> 2) + (x >> 3)) & 3) << 6)) >> logBpp;
+ }
+
+ static void Swap(byte[] d, int endian)
+ {
+ if (endian == 1) for (int i = 0; i + 1 < d.Length; i += 2) (d[i], d[i + 1]) = (d[i + 1], d[i]);
+ else if (endian == 2) for (int i = 0; i + 3 < d.Length; i += 4) { (d[i], d[i + 3]) = (d[i + 3], d[i]); (d[i + 1], d[i + 2]) = (d[i + 2], d[i + 1]); }
+ else if (endian == 3) for (int i = 0; i + 3 < d.Length; i += 4) { (d[i], d[i + 2]) = (d[i + 2], d[i]); (d[i + 1], d[i + 3]) = (d[i + 3], d[i + 1]); }
+ }
+
+ static byte[] Argb(byte[] s, int width, int height)
+ {
+ // After the byte swap 8_8_8_8 is stored B, G, R, A in memory.
+ var rgba = new byte[width * height * 4];
+ for (int i = 0; i < width * height; i++)
+ { rgba[i * 4] = s[i * 4 + 2]; rgba[i * 4 + 1] = s[i * 4 + 1]; rgba[i * 4 + 2] = s[i * 4]; rgba[i * 4 + 3] = s[i * 4 + 3]; }
+ return rgba;
+ }
+
+ static byte[] Gray(byte[] s, int width, int height)
+ {
+ var rgba = new byte[width * height * 4];
+ for (int i = 0; i < width * height; i++) { rgba[i * 4] = rgba[i * 4 + 1] = rgba[i * 4 + 2] = 255; rgba[i * 4 + 3] = s[i]; }
+ return rgba;
+ }
+
+ // ---- DXT ----------------------------------------------------------------------------------
+
+ static byte[] Dxt(ReadOnlySpan<byte> s, int width, int height, int kind, int blocksPerRow = 0)
+ {
+ int bw = (width + 3) / 4, bh = (height + 3) / 4, size = kind == 1 ? 8 : 16;
+ if (blocksPerRow == 0) blocksPerRow = bw;
+ var rgba = new byte[width * height * 4];
+ Span<byte> colors = stackalloc byte[16], alpha = stackalloc byte[16];
+ for (int by = 0; by < bh; by++)
+ for (int bx = 0; bx < bw; bx++)
+ {
+ int at = (by * blocksPerRow + bx) * size;
+ if (at + size > s.Length) continue;
+ var block = s.Slice(at, size);
+ alpha.Fill(255);
+ if (kind == 3) for (int i = 0; i < 16; i++) alpha[i] = (byte)(((block[i / 2] >> (i % 2 * 4)) & 15) * 17);
+ if (kind == 5)
+ {
+ int a0 = block[0], a1 = block[1]; ulong bits = 0;
+ for (int i = 0; i < 6; i++) bits |= (ulong)block[2 + i] << (8 * i);
+ for (int i = 0; i < 16; i++)
+ {
+ int code = (int)((bits >> (3 * i)) & 7);
+ alpha[i] = (byte)(code == 0 ? a0 : code == 1 ? a1 : a0 > a1 ? ((8 - code) * a0 + (code - 1) * a1) / 7
+ : code == 6 ? 0 : code == 7 ? 255 : ((6 - code) * a0 + (code - 1) * a1) / 5);
+ }
+ }
+ var c = block.Slice(kind == 1 ? 0 : 8, 8);
+ int c0 = c[0] | (c[1] << 8), c1 = c[2] | (c[3] << 8);
+ Rgb565(c0, colors[..4]); Rgb565(c1, colors.Slice(4, 4));
+ bool four = kind != 1 || c0 > c1;
+ for (int k = 0; k < 3; k++)
+ {
+ colors[8 + k] = (byte)(four ? (2 * colors[k] + colors[4 + k]) / 3 : (colors[k] + colors[4 + k]) / 2);
+ colors[12 + k] = (byte)(four ? (colors[k] + 2 * colors[4 + k]) / 3 : 0);
+ }
+ colors[11] = 255; colors[15] = (byte)(four ? 255 : 0);
+ uint idx = (uint)(c[4] | (c[5] << 8) | (c[6] << 16) | (c[7] << 24));
+ for (int i = 0; i < 16; i++)
+ {
+ int x = bx * 4 + i % 4, y = by * 4 + i / 4;
+ if (x >= width || y >= height) continue;
+ int code = (int)((idx >> (2 * i)) & 3), o = (y * width + x) * 4;
+ rgba[o] = colors[code * 4]; rgba[o + 1] = colors[code * 4 + 1]; rgba[o + 2] = colors[code * 4 + 2];
+ rgba[o + 3] = kind == 1 ? colors[code * 4 + 3] : alpha[i];
+ }
+ }
+ return rgba;
+ }
+
+ // Bounding-box DXT5 encoder: good for the game's flat, mostly two-tone UI art.
+ internal static byte[] EncodeDxt5(byte[] rgba, int width, int height)
+ {
+ int bw = (width + 3) / 4, bh = (height + 3) / 4;
+ var output = new byte[bw * bh * 16];
+ Span<int> px = stackalloc int[64];
+ Span<int> palette = stackalloc int[12];
+ Span<int> alphas = stackalloc int[8];
+ Span<byte> e = stackalloc byte[8];
+ Span<double> e0 = stackalloc double[3], e1 = stackalloc double[3], sx = stackalloc double[3], sy = stackalloc double[3];
+ for (int by = 0; by < bh; by++)
+ for (int bx = 0; bx < bw; bx++)
+ {
+ for (int i = 0; i < 16; i++)
+ {
+ int x = Math.Min(bx * 4 + i % 4, width - 1), y = Math.Min(by * 4 + i / 4, height - 1), o = (y * width + x) * 4;
+ for (int k = 0; k < 4; k++) px[i * 4 + k] = rgba[o + k];
+ }
+ var block = output.AsSpan((by * bw + bx) * 16, 16);
+
+ int a0 = 0, a1 = 255;
+ for (int i = 0; i < 16; i++) { a0 = Math.Max(a0, px[i * 4 + 3]); a1 = Math.Min(a1, px[i * 4 + 3]); }
+ block[0] = (byte)a0; block[1] = (byte)a1;
+ alphas[0] = a0; alphas[1] = a1;
+ for (int i = 1; i <= 6; i++) alphas[i + 1] = ((7 - i) * a0 + i * a1) / 7;
+ ulong abits = 0;
+ for (int i = 0; i < 16; i++)
+ {
+ int best = 0;
+ for (int c = 1; c < 8 && a0 != a1; c++) if (Math.Abs(alphas[c] - px[i * 4 + 3]) < Math.Abs(alphas[best] - px[i * 4 + 3])) best = c;
+ abits |= (ulong)best << (3 * i);
+ }
+ for (int i = 0; i < 6; i++) block[2 + i] = (byte)(abits >> (8 * i));
+
+ // Colour endpoints: the darkest and brightest visible texels.
+ int lo = -1, hi = -1;
+ for (int i = 0; i < 16; i++)
+ {
+ if (px[i * 4 + 3] == 0 && a0 > 0) continue;
+ int l = px[i * 4] * 3 + px[i * 4 + 1] * 6 + px[i * 4 + 2];
+ if (lo < 0 || l < px[lo * 4] * 3 + px[lo * 4 + 1] * 6 + px[lo * 4 + 2]) lo = i;
+ if (hi < 0 || l > px[hi * 4] * 3 + px[hi * 4 + 1] * 6 + px[hi * 4 + 2]) hi = i;
+ }
+ if (lo < 0) lo = hi = 0;
+
+ // Start from the darkest and brightest texels, then refine both endpoints by least
+ // squares a few times and keep the best block, so small coloured details survive.
+ e0[0] = px[hi * 4]; e0[1] = px[hi * 4 + 1]; e0[2] = px[hi * 4 + 2];
+ e1[0] = px[lo * 4]; e1[1] = px[lo * 4 + 1]; e1[2] = px[lo * 4 + 2];
+ long bestError = long.MaxValue; int bestC0 = 0, bestC1 = 0; uint bestBits = 0;
+ for (int pass = 0; pass < 4; pass++)
+ {
+ int c0 = To565((int)Math.Round(e0[0]), (int)Math.Round(e0[1]), (int)Math.Round(e0[2]));
+ int c1 = To565((int)Math.Round(e1[0]), (int)Math.Round(e1[1]), (int)Math.Round(e1[2]));
+ if (c0 < c1) (c0, c1) = (c1, c0);
+ Rgb565(c0, e[..4]); Rgb565(c1, e.Slice(4, 4));
+ for (int k = 0; k < 3; k++)
+ {
+ palette[k] = e[k]; palette[3 + k] = e[4 + k];
+ palette[6 + k] = (2 * e[k] + e[4 + k]) / 3; palette[9 + k] = (e[k] + 2 * e[4 + k]) / 3;
+ }
+ uint cbits = 0; long error = 0;
+ double sa = 0, sb = 0, sc = 0;
+ sx.Clear(); sy.Clear();
+ for (int i = 0; i < 16; i++)
+ {
+ int best = 0, bestDistance = int.MaxValue;
+ for (int c = 0; c < (c0 == c1 ? 1 : 4); c++)
+ {
+ int dr = palette[c * 3] - px[i * 4], dg = palette[c * 3 + 1] - px[i * 4 + 1], db = palette[c * 3 + 2] - px[i * 4 + 2];
+ int distance = dr * dr + dg * dg + db * db;
+ if (distance < bestDistance) { best = c; bestDistance = distance; }
+ }
+ cbits |= (uint)best << (2 * i);
+ if (px[i * 4 + 3] == 0 && a0 > 0) continue; // invisible texels do not count
+ error += bestDistance;
+ double w = best switch { 0 => 1, 1 => 0, 2 => 2 / 3.0, _ => 1 / 3.0 };
+ sa += w * w; sb += w * (1 - w); sc += (1 - w) * (1 - w);
+ for (int k = 0; k < 3; k++) { sx[k] += w * px[i * 4 + k]; sy[k] += (1 - w) * px[i * 4 + k]; }
+ }
+ if (error < bestError) { bestError = error; bestC0 = c0; bestC1 = c1; bestBits = cbits; }
+ double det = sa * sc - sb * sb;
+ if (error == 0 || Math.Abs(det) < 1e-6) break;
+ for (int k = 0; k < 3; k++)
+ {
+ e0[k] = Math.Clamp((sc * sx[k] - sb * sy[k]) / det, 0, 255);
+ e1[k] = Math.Clamp((sa * sy[k] - sb * sx[k]) / det, 0, 255);
+ }
+ }
+ block[8] = (byte)bestC0; block[9] = (byte)(bestC0 >> 8); block[10] = (byte)bestC1; block[11] = (byte)(bestC1 >> 8);
+ block[12] = (byte)bestBits; block[13] = (byte)(bestBits >> 8); block[14] = (byte)(bestBits >> 16); block[15] = (byte)(bestBits >> 24);
+ }
+ return output;
+ }
+
+ static int To565(int r, int g, int b) => ((r * 31 + 127) / 255 << 11) | ((g * 63 + 127) / 255 << 5) | ((b * 31 + 127) / 255);
+
+ // Minimal PNG reader for the patcher's own glyphs (8-bit grey/RGB/RGBA, not interlaced).
+ internal static (byte[] Rgba, int Width, int Height) ReadPng(byte[] png)
+ {
+ int width = 0, height = 0, type = 0, p = 8;
+ using var idat = new MemoryStream();
+ while (p + 8 <= png.Length)
+ {
+ int length = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(p)); string chunk = Encoding.ASCII.GetString(png, p + 4, 4);
+ if (chunk == "IHDR")
+ {
+ width = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(p + 8)); height = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(p + 12));
+ if (png[p + 16] != 8 || png[p + 20] != 0) throw new InvalidDataException("Only 8-bit, non-interlaced PNG glyphs are supported.");
+ type = png[p + 17];
+ }
+ else if (chunk == "IDAT") idat.Write(png, p + 8, length);
+ p += 12 + length;
+ }
+ int channels = type switch { 0 => 1, 2 => 3, 4 => 2, 6 => 4, _ => throw new InvalidDataException("Unsupported PNG colour type.") };
+ using var z = new ZLibStream(new MemoryStream(idat.ToArray()), CompressionMode.Decompress);
+ using var raw = new MemoryStream(); z.CopyTo(raw); byte[] data = raw.ToArray();
+ int stride = width * channels; var previous = new byte[stride]; var row = new byte[stride]; var rgba = new byte[width * height * 4];
+ for (int y = 0; y < height; y++)
+ {
+ int filter = data[y * (stride + 1)]; Buffer.BlockCopy(data, y * (stride + 1) + 1, row, 0, stride);
+ for (int i = 0; i < stride; i++)
+ {
+ int a = i >= channels ? row[i - channels] : 0, b = previous[i], c = i >= channels ? previous[i - channels] : 0;
+ int pa = Math.Abs(b - c), pb = Math.Abs(a - c), pc = Math.Abs(a + b - 2 * c);
+ row[i] = (byte)(row[i] + filter switch { 1 => a, 2 => b, 3 => (a + b) / 2, 4 => pa <= pb && pa <= pc ? a : pb <= pc ? b : c, _ => 0 });
+ }
+ for (int x = 0; x < width; x++)
+ {
+ int o = (y * width + x) * 4, s = x * channels;
+ (rgba[o], rgba[o + 1], rgba[o + 2], rgba[o + 3]) = channels switch
+ {
+ 1 => (row[s], row[s], row[s], (byte)255),
+ 2 => (row[s], row[s], row[s], row[s + 1]),
+ 3 => (row[s], row[s + 1], row[s + 2], (byte)255),
+ _ => (row[s], row[s + 1], row[s + 2], row[s + 3]),
+ };
+ }
+ (previous, row) = (row, previous);
+ }
+ return (rgba, width, height);
+ }
+
+ internal static byte[] ToPng(byte[] rgba, int width, int height) => Png(rgba, width, height);
+
+ static void Rgb565(int v, Span<byte> o)
+ {
+ o[0] = (byte)(((v >> 11) & 31) * 255 / 31); o[1] = (byte)(((v >> 5) & 63) * 255 / 63); o[2] = (byte)((v & 31) * 255 / 31); o[3] = 255;
+ }
+
+ // ---- PNG ----------------------------------------------------------------------------------
+
+ static byte[] Png(byte[] rgba, int width, int height)
+ {
+ using var raw = new MemoryStream();
+ using (var z = new ZLibStream(raw, CompressionLevel.Optimal, leaveOpen: true))
+ for (int y = 0; y < height; y++) { z.WriteByte(0); z.Write(rgba, y * width * 4, width * 4); }
+ using var png = new MemoryStream();
+ png.Write(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 });
+ var ihdr = new byte[13];
+ BinaryPrimitives.WriteInt32BigEndian(ihdr, width); BinaryPrimitives.WriteInt32BigEndian(ihdr.AsSpan(4), height);
+ ihdr[8] = 8; ihdr[9] = 6;
+ Chunk(png, "IHDR", ihdr); Chunk(png, "IDAT", raw.ToArray()); Chunk(png, "IEND", Array.Empty<byte>());
+ return png.ToArray();
+ }
+
+ static void Chunk(Stream s, string type, byte[] data)
+ {
+ var head = new byte[8]; BinaryPrimitives.WriteInt32BigEndian(head, data.Length); Encoding.ASCII.GetBytes(type).CopyTo(head, 4);
+ s.Write(head); s.Write(data);
+ uint crc = Crc(Crc(0xFFFFFFFF, head.AsSpan(4)), data) ^ 0xFFFFFFFF;
+ var tail = new byte[4]; BinaryPrimitives.WriteUInt32BigEndian(tail, crc); s.Write(tail);
+ }
+
+ static readonly uint[] CrcTable = Enumerable.Range(0, 256).Select(n =>
+ {
+ uint c = (uint)n;
+ for (int k = 0; k < 8; k++) c = (c & 1) != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1;
+ return c;
+ }).ToArray();
+
+ static uint Crc(uint crc, ReadOnlySpan<byte> data)
+ {
+ foreach (byte v in data) crc = CrcTable[(crc ^ v) & 0xFF] ^ (crc >> 8);
+ return crc;
+ }
+
+ static uint BE(byte[] b, int p) => BinaryPrimitives.ReadUInt32BigEndian(b.AsSpan(p, 4));
+}
diff --git a/Tools/ReStreetAssetScan/pack.ps1 b/Tools/ReStreetAssetScan/pack.ps1
new file mode 100644
index 0000000..bdd54c5
--- /dev/null
+++ b/Tools/ReStreetAssetScan/pack.ps1
@@ -0,0 +1,92 @@
+# Builds the ready-to-use DualSense package: one self-contained exe (no .NET needed), the art
+# folder and two double-click shortcuts.
+#
+# powershell -ExecutionPolicy Bypass -File Tools/ReStreetAssetScan/pack.ps1 [-Art private/dualsense-art] [-Output dist/ReStreet-DualSense]
+# [-Originals private/dualsense*.png,private/*.json] [-References private/dualsense-reference/*.png]
+#
+# -Art adds or replaces art in the package's DualSense folder (for example the Select Sides and
+# controls-screen pictures built from your own controller picture). Pictures you did not make
+# yourself may not be yours to share; check before giving the package to anyone.
+param(
+ [string]$Art = "",
+ [string]$Output = "dist/ReStreet-DualSense",
+ [string[]]$Originals = @(), # files or wildcards copied to Imagens-originais
+ [string[]]$References = @() # files or wildcards copied to Referencias
+)
+$ErrorActionPreference = "Stop"
+$project = Join-Path $PSScriptRoot "ReStreetAssetScan.csproj"
+$out = [IO.Path]::GetFullPath($Output)
+# Empty the folder rather than deleting it, so it works while an Explorer window shows it.
+if (Test-Path $out) { Get-ChildItem $out -Force | Remove-Item -Recurse -Force }
+
+dotnet publish $project -c Release -r win-x64 --self-contained true -nologo -v q `
+ -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:AssemblyName=ReStreetDualSense -o $out
+if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed" }
+Get-ChildItem $out -Filter *.pdb | Remove-Item
+
+if ($Art -ne "") {
+ $artDir = [IO.Path]::GetFullPath($Art)
+ if (-not (Test-Path $artDir)) { throw "Art folder not found: $artDir" }
+ Copy-Item (Join-Path $artDir "*.png") (Join-Path $out "DualSense") -Force
+}
+
+# The report and the tool's source travel with the package.
+New-Item -ItemType Directory -Force (Join-Path $out "Relatorio") | Out-Null
+Copy-Item (Join-Path $PSScriptRoot "RELATORIO-DUALSENSE.md") (Join-Path $out "Relatorio")
+$source = Join-Path $out "Codigo-fonte"
+New-Item -ItemType Directory -Force $source | Out-Null
+Get-ChildItem $PSScriptRoot -Exclude bin, obj | Copy-Item -Destination $source -Recurse
+Copy-Item (Join-Path $PSScriptRoot "..\..\Installer\FifaStreetSetupTool\ThirdParty\LzxDecoder.cs") $source
+Copy-Item (Join-Path $PSScriptRoot "..\..\Installer\FifaStreetSetupTool\ThirdParty\MonoGame-LICENSE.txt") $source
+# The copied project picks up its own LzxDecoder.cs by default, so drop the link to the installer's.
+$csproj = Join-Path $source "ReStreetAssetScan.csproj"
+(Get-Content $csproj | Where-Object { $_ -notmatch 'LzxDecoder\.cs' }) | Set-Content $csproj -Encoding utf8
+
+# Optional extras: the pictures the art was made from, and the reference sheets.
+foreach ($pair in @(@($Originals, "Imagens-originais"), @($References, "Referencias"))) {
+ # "powershell -File" passes a comma list as one string, so split it here.
+ $files = @($pair[0] | ForEach-Object { $_ -split ',' } | Where-Object { $_.Trim() -ne "" } | ForEach-Object { Get-ChildItem $_.Trim() -File })
+ if ($files.Count -eq 0) { continue }
+ $dest = Join-Path $out $pair[1]
+ New-Item -ItemType Directory -Force $dest | Out-Null
+ $files | Copy-Item -Destination $dest
+}
+
+$utf8 = New-Object System.Text.UTF8Encoding($false)
+[IO.File]::WriteAllText((Join-Path $out "Instalar DualSense.cmd"), "@echo off`r`nchcp 65001 >nul`r`n`"%~dp0ReStreetDualSense.exe`" install %*`r`n", $utf8)
+[IO.File]::WriteAllText((Join-Path $out "Remover DualSense.cmd"), "@echo off`r`nchcp 65001 >nul`r`n`"%~dp0ReStreetDualSense.exe`" uninstall %*`r`n", $utf8)
+$readme = @"
+ReStreet - botões de PlayStation 5 (DualSense)
+
+INSTALAR
+ 1. Feche o FIFA Street (o launcher pode ficar aberto).
+ 2. Dê dois cliques em "Instalar DualSense.cmd".
+ A instalação do ReStreet é encontrada sozinha (pelo atalho do launcher).
+ Se não for, arraste a pasta do ReStreet (a que tem o FifaStreetLauncher.exe)
+ para cima de "Instalar DualSense.cmd".
+
+REMOVER
+ Dê dois cliques em "Remover DualSense.cmd". O jogo volta exatamente como era.
+
+ANTES DE ATUALIZAR O RESTREET
+ Use "Remover DualSense.cmd", atualize pelo launcher e depois instale de novo.
+
+O QUE MUDA
+ Botões dos menus e do HUD, lista e dicas de skill moves, o controle da seleção
+ de lados e as telas de controles (loading, Manual do Jogo, configurações).
+ Só data0.big, data1.big e seus .bh são alterados; um backup fica ao lado deles
+ (*.dualsense-backup) e é o que o "Remover" usa.
+
+Também dá para usar pelo terminal:
+ ReStreetDualSense.exe install|uninstall|status [pasta do ReStreet]
+
+NESTA PASTA
+ Relatorio\ relatório técnico (o que muda, como e por quê)
+ Codigo-fonte\ código da ferramenta (no projeto: Tools\ReStreetAssetScan)
+ DualSense\ a arte que o instalador aplica
+ Imagens-originais\, Referencias\ (quando incluídas) as imagens de origem e as folhas de referência
+"@
+[IO.File]::WriteAllText((Join-Path $out "LEIA-ME.txt"), $readme.Replace("`n", "`r`n"), $utf8)
+
+Write-Host "Package ready: $out"
+Get-ChildItem $out | Format-Table Name, Length -AutoSize