// v2 never calls binary ReadFile. A deployment helper extracts the 8-bit Value // raster to RLE text; this loader reads it with FGets, reconstructs the original // AFR_IntPage layout incrementally, and leaves the v1 Tier1 fallback in place. modded class AFR_AreaFlagsService { protected static const int SFL_COMPAT_STATE_UNINITIALIZED = 0; protected static const int SFL_COMPAT_STATE_LOADING = 1; protected static const int SFL_COMPAT_STATE_READY = 2; protected static const int SFL_COMPAT_STATE_FALLBACK = 3; protected static const int SFL_COMPAT_FORMAT_VERSION = 2; protected static const int SFL_COMPAT_MAX_PIXELS = 16777216; protected static const int SFL_COMPAT_MAX_RUNS = 1000000; protected static const int SFL_COMPAT_MAX_PACKED_WRITES_PER_TICK = 8192; protected static const int SFL_COMPAT_MAX_RUN_LINES_PER_TICK = 64; protected static const int SFL_COMPAT_MAX_TEST_POSITIONS = 16; protected static const int SFL_COMPAT_LOAD_TIMEOUT_MS = 120000; protected static const string SFL_COMPAT_TIER_PATH = "$mission:sfl_arm_tiers_v2.rle"; protected static const string SFL_COMPAT_TEST_PATH = "$mission:sfl_arm_tier_tests.csv"; protected int m_SFLCompatState; protected int m_SFLCompatPendingValue; protected int m_SFLCompatPendingCells; protected int m_SFLCompatRunCount; protected int m_SFLCompatProgressMilestone; protected int m_SFLCompatValueOffset; protected int m_SFLCompatSourceSize; protected string m_SFLCompatSourceSha256; override void Start(string path = "$mission:areaflags.map") { if (!GetGame() || !GetGame().IsServer()) { Print("[SFL ARM COMPAT] v2 tier loader ignored - not running on server"); return; } if (m_IsLoading || m_IsReady) { PrintFormat("[SFL ARM COMPAT] v2 tier loader already active | state=%1", GetSFLCompatTierState()); return; } SFLCompatRemoveLoadStep(); ResetState(); SFLCompatResetFields(); m_Path = SFL_COMPAT_TIER_PATH; Print("[SFL ARM COMPAT] v2 starting AreaFlags tier loader"); if (!FileExist(m_Path)) { SFLCompatEnterFallback("tier RLE file not found: " + m_Path); return; } m_File = OpenFile(m_Path, FileMode.READ); if (m_File == 0) { SFLCompatEnterFallback("OpenFile failed: " + m_Path); return; } m_FileOpen = true; string headerError; if (!SFLCompatReadHeader(headerError)) { SFLCompatEnterFallback(headerError); return; } m_ValuePages = new array; m_UsageBytesSkipped = m_PixelCount * 4; m_ValueCellsRead = 0; m_LoadStage = AFR_STAGE_VALUE; m_IsLoading = true; m_IsReady = false; m_HasFailed = false; m_LoadStartedAt = GetGame().GetTime(); m_SFLCompatState = SFL_COMPAT_STATE_LOADING; PrintFormat("[SFL ARM COMPAT] header OK | raster=%1x%2 | world=%3x%4m | cell=%5x%6m | valueBits=%7", m_Width, m_Height, m_WorldWidth, m_WorldHeight, m_CellSizeX, m_CellSizeZ, m_ValueBitsPerPixel); PrintFormat("[SFL ARM COMPAT] Usage raster bypassed safely | usageBytes=%1 | valueOffset=%2 | sourceBytes=%3", m_UsageBytesSkipped, m_SFLCompatValueOffset, m_SFLCompatSourceSize); PrintFormat("[SFL ARM COMPAT] source SHA-256=%1", m_SFLCompatSourceSha256); SFLCompatScheduleLoadStep(); } override void Stop() { SFLCompatRemoveLoadStep(); m_SFLCompatState = SFL_COMPAT_STATE_UNINITIALIZED; super.Stop(); } string GetSFLCompatTierState() { switch (m_SFLCompatState) { case SFL_COMPAT_STATE_LOADING: return "LOADING"; case SFL_COMPAT_STATE_READY: return "READY"; case SFL_COMPAT_STATE_FALLBACK: return "FALLBACK"; } return "UNINITIALIZED"; } // v1 remains a hard safety net. This method should not be reached by the v2 // text loader, but it still blocks the exact native call from the crash stack. override protected bool SkipAreaFlagsUsageChunk() { int usageByteCount = m_PixelCount * 4; int remainingBytes = usageByteCount - m_UsageBytesSkipped; int requestedBytes = AFR_READ_CHUNK_BYTES; if (remainingBytes < requestedBytes) requestedBytes = remainingBytes; if (requestedBytes < 0) requestedBytes = 0; int chunkIndex = 0; if (AFR_READ_CHUNK_BYTES > 0) chunkIndex = m_UsageBytesSkipped / AFR_READ_CHUNK_BYTES; int logicalFileOffset = AFR_HEADER_SIZE + m_UsageBytesSkipped; Print("[SFL ARM COMPAT] v1 AreaFlags Usage-raster ReadFile safety gate active"); PrintFormat("[SFL ARM COMPAT] unsafe Usage read BYPASSED | stage=%1 | logicalFileOffset=%2 | requestedBytes=%3 | chunkIndex=%4 | raster=%5x%6 | remainingBytes=%7 | usageSkipped=%8/%9", m_LoadStage, logicalFileOffset, requestedBytes, chunkIndex, m_Width, m_Height, remainingBytes, m_UsageBytesSkipped, usageByteCount); SFLCompatEnterFallback("v1 gate stopped the optional AreaFlags loader before the unsafe Usage ReadFile call"); return false; } protected void SFLCompatResetFields() { m_SFLCompatState = SFL_COMPAT_STATE_UNINITIALIZED; m_SFLCompatPendingValue = 0; m_SFLCompatPendingCells = 0; m_SFLCompatRunCount = 0; m_SFLCompatProgressMilestone = 0; m_SFLCompatValueOffset = 0; m_SFLCompatSourceSize = 0; m_SFLCompatSourceSha256 = ""; } protected bool SFLCompatReadHeader(out string error) { error = ""; string line; if (SFLCompatReadLine(line) <= 0) { error = "tier RLE header is missing"; return false; } TStringArray header = new TStringArray; line.Split(",", header); if (header.Count() != 14 || header.Get(0) != "SFL_ARM_TIERS_V2") { error = "invalid tier RLE magic/header field count"; return false; } for (int i = 1; i < header.Count(); i++) { if (!SFLCompatIsUnsignedDecimal(header.Get(i))) { error = "non-numeric tier RLE header field at index " + i.ToString(); return false; } } int version = header.Get(1).ToInt(); int width = header.Get(2).ToInt(); int height = header.Get(3).ToInt(); int worldWidth = header.Get(4).ToInt(); int worldHeight = header.Get(5).ToInt(); int usageBits = header.Get(6).ToInt(); int valueBits = header.Get(7).ToInt(); int declaredPixelCount = header.Get(8).ToInt(); int usageOffset = header.Get(9).ToInt(); int declaredUsageBytes = header.Get(10).ToInt(); int valueHeaderOffset = header.Get(11).ToInt(); int valueOffset = header.Get(12).ToInt(); int sourceSize = header.Get(13).ToInt(); if (version != SFL_COMPAT_FORMAT_VERSION) { error = "unsupported tier RLE version: " + version.ToString(); return false; } if (width <= 0 || height <= 0 || worldWidth <= 0 || worldHeight <= 0) { error = "invalid raster/world dimensions in tier RLE header"; return false; } if (height > SFL_COMPAT_MAX_PIXELS || width > (SFL_COMPAT_MAX_PIXELS / height)) { error = "tier RLE pixel count exceeds safety limit"; return false; } int pixelCount = width * height; if (pixelCount != declaredPixelCount || pixelCount <= 0) { error = "tier RLE pixel count does not match dimensions"; return false; } if (usageBits != 32 || valueBits != 8) { error = "unsupported Usage/Value bit depth in tier RLE header"; return false; } int expectedUsageBytes = pixelCount * 4; int expectedValueHeaderOffset = AFR_HEADER_SIZE + expectedUsageBytes; int expectedValueOffset = expectedValueHeaderOffset + 4; int expectedMinimumSourceSize = expectedValueOffset + pixelCount; if (usageOffset != AFR_HEADER_SIZE || declaredUsageBytes != expectedUsageBytes || valueHeaderOffset != expectedValueHeaderOffset || valueOffset != expectedValueOffset) { error = "tier RLE offsets do not match the AreaFlags layout"; return false; } if (sourceSize < expectedMinimumSourceSize) { error = "source size in tier RLE header is too small"; return false; } if (SFLCompatReadLine(line) <= 0) { error = "tier RLE SOURCE_SHA256 line is missing"; return false; } TStringArray shaLine = new TStringArray; line.Split(",", shaLine); if (shaLine.Count() != 2 || shaLine.Get(0) != "SOURCE_SHA256" || !SFLCompatIsSha256(shaLine.Get(1))) { error = "invalid tier RLE SOURCE_SHA256 line"; return false; } if (SFLCompatReadLine(line) <= 0 || line != "DATA") { error = "tier RLE DATA marker is missing"; return false; } m_Width = width; m_Height = height; m_WorldWidth = worldWidth; m_WorldHeight = worldHeight; m_UsageBitsPerPixel = usageBits; m_ValueBitsPerPixel = valueBits; m_PixelCount = pixelCount; m_CellSizeX = (m_WorldWidth * 1.0) / m_Width; m_CellSizeZ = (m_WorldHeight * 1.0) / m_Height; m_SFLCompatValueOffset = valueOffset; m_SFLCompatSourceSize = sourceSize; m_SFLCompatSourceSha256 = shaLine.Get(1); return true; } protected void SFLCompatScheduleLoadStep() { if (!m_IsLoading || m_SFLCompatState != SFL_COMPAT_STATE_LOADING || !GetGame()) return; GetGame().GetCallQueue(CALL_CATEGORY_GAMEPLAY).CallLater(SFLCompatProcessTierLoadStep, 1, false); } protected void SFLCompatRemoveLoadStep() { if (GetGame()) GetGame().GetCallQueue(CALL_CATEGORY_GAMEPLAY).Remove(SFLCompatProcessTierLoadStep); } protected void SFLCompatProcessTierLoadStep() { if (!m_IsLoading || m_HasFailed || m_SFLCompatState != SFL_COMPAT_STATE_LOADING) return; if ((GetGame().GetTime() - m_LoadStartedAt) > SFL_COMPAT_LOAD_TIMEOUT_MS) { SFLCompatEnterFallback("tier RLE load exceeded the 120-second safety timeout"); return; } int packedWrites = 0; int linesRead = 0; while (packedWrites < SFL_COMPAT_MAX_PACKED_WRITES_PER_TICK && linesRead < SFL_COMPAT_MAX_RUN_LINES_PER_TICK) { if (m_SFLCompatPendingCells > 0) { int writesUsed = SFLCompatWritePendingRun(SFL_COMPAT_MAX_PACKED_WRITES_PER_TICK - packedWrites); packedWrites += writesUsed; if (m_SFLCompatPendingCells > 0) break; continue; } string line; int charsRead = SFLCompatReadLine(line); if (charsRead < 0) { SFLCompatEnterFallback("unexpected EOF before tier RLE END marker"); return; } if (charsRead == 0) { SFLCompatEnterFallback("blank line in tier RLE data section"); return; } linesRead++; if (line.IndexOf("END,") == 0) { if (!SFLCompatFinishFromEndMarker(line)) return; return; } int runValue; int runCells; string runError; if (!SFLCompatParseRun(line, runValue, runCells, runError)) { SFLCompatEnterFallback(runError); return; } int remainingCells = m_PixelCount - m_ValueCellsRead; if (runCells > remainingCells) { SFLCompatEnterFallback("tier RLE run exceeds declared pixel count"); return; } m_SFLCompatRunCount++; if (m_SFLCompatRunCount > SFL_COMPAT_MAX_RUNS) { SFLCompatEnterFallback("tier RLE run count exceeds safety limit"); return; } m_SFLCompatPendingValue = runValue; m_SFLCompatPendingCells = runCells; } SFLCompatLogProgress(); SFLCompatScheduleLoadStep(); } protected int SFLCompatWritePendingRun(int maxPackedWrites) { int writesUsed = 0; while (m_SFLCompatPendingCells > 0 && m_ValueCellsRead < m_PixelCount && writesUsed < maxPackedWrites) { int packedIndex = m_ValueCellsRead / 4; int pageIndex = packedIndex / AFR_PAGE_INT_COUNT; int pageOffset = packedIndex % AFR_PAGE_INT_COUNT; int byteOffset = m_ValueCellsRead & 3; while (m_ValuePages.Count() <= pageIndex) m_ValuePages.Insert(new AFR_IntPage(AFR_PAGE_INT_COUNT)); AFR_IntPage page = m_ValuePages.Get(pageIndex); int packedValue = page.Data.Get(pageOffset); int cellsThisWrite = 4 - byteOffset; if (cellsThisWrite > m_SFLCompatPendingCells) cellsThisWrite = m_SFLCompatPendingCells; int remainingCells = m_PixelCount - m_ValueCellsRead; if (cellsThisWrite > remainingCells) cellsThisWrite = remainingCells; for (int i = 0; i < cellsThisWrite; i++) packedValue = packedValue | ((m_SFLCompatPendingValue & 255) << ((byteOffset + i) * 8)); page.Data.Set(pageOffset, packedValue); m_ValueCellsRead += cellsThisWrite; m_SFLCompatPendingCells -= cellsThisWrite; writesUsed++; } return writesUsed; } protected bool SFLCompatFinishFromEndMarker(string line) { TStringArray endLine = new TStringArray; line.Split(",", endLine); if (endLine.Count() != 3 || endLine.Get(0) != "END" || !SFLCompatIsUnsignedDecimal(endLine.Get(1)) || !SFLCompatIsUnsignedDecimal(endLine.Get(2))) { SFLCompatEnterFallback("invalid tier RLE END marker"); return false; } int declaredRuns = endLine.Get(1).ToInt(); int declaredCells = endLine.Get(2).ToInt(); if (declaredRuns != m_SFLCompatRunCount || declaredCells != m_ValueCellsRead || m_ValueCellsRead != m_PixelCount) { SFLCompatEnterFallback("tier RLE END counts do not match decoded data"); return false; } int cellsPerPage = AFR_PAGE_INT_COUNT * 4; int expectedPages = (m_PixelCount + cellsPerPage - 1) / cellsPerPage; if (!m_ValuePages || m_ValuePages.Count() != expectedPages) { SFLCompatEnterFallback("tier RLE decoded page count is invalid"); return false; } m_SFLCompatProgressMilestone = 100; Print("[SFL ARM COMPAT] Tier raster load progress=100%"); m_SFLCompatState = SFL_COMPAT_STATE_READY; FinishLoading(); if (!m_IsReady) { SFLCompatEnterFallback("base AreaFlags verification rejected decoded tier data"); return false; } PrintFormat("[SFL ARM COMPAT] Tier raster READY | cells=%1 | runs=%2 | pages=%3 | memory~16 MiB", m_ValueCellsRead, m_SFLCompatRunCount, m_ValuePages.Count()); SFLCompatLogProbes(); return true; } protected void SFLCompatLogProgress() { if (m_PixelCount <= 0) return; int progress = Math.Floor((m_ValueCellsRead * 100.0) / m_PixelCount); if (progress >= 25 && m_SFLCompatProgressMilestone < 25) { m_SFLCompatProgressMilestone = 25; Print("[SFL ARM COMPAT] Tier raster load progress=25%"); } if (progress >= 50 && m_SFLCompatProgressMilestone < 50) { m_SFLCompatProgressMilestone = 50; Print("[SFL ARM COMPAT] Tier raster load progress=50%"); } if (progress >= 75 && m_SFLCompatProgressMilestone < 75) { m_SFLCompatProgressMilestone = 75; Print("[SFL ARM COMPAT] Tier raster load progress=75%"); } } protected void SFLCompatLogProbes() { if (FileExist(SFL_COMPAT_TEST_PATH)) { FileHandle testFile = OpenFile(SFL_COMPAT_TEST_PATH, FileMode.READ); if (testFile != 0) { int testsLogged = 0; int linesRead = 0; string line; while (testsLogged < SFL_COMPAT_MAX_TEST_POSITIONS && linesRead < (SFL_COMPAT_MAX_TEST_POSITIONS * 2)) { int charsRead = FGets(testFile, line); if (charsRead < 0) break; linesRead++; line = SFLCompatTrimLineEndings(line); if (line == "" || line.IndexOf("#") == 0) continue; TStringArray test = new TStringArray; line.Split(",", test); if (test.Count() != 4) { PrintFormat("[SFL ARM COMPAT] Tier lookup test skipped | invalid line=%1", linesRead); continue; } float x = test.Get(1).ToFloat(); float z = test.Get(2).ToFloat(); vector testPosition = Vector(x, 0, z); int testValue; if (!TryGetValueFlags(testPosition, testValue)) { PrintFormat("[SFL ARM COMPAT] Tier lookup test FAILED | label=%1 | position=%2 | reason=outside-map", test.Get(0), testPosition); testsLogged++; continue; } string actualTier = SFLCompatValueText(testValue); bool matches = actualTier == test.Get(3); PrintFormat("[SFL ARM COMPAT] Tier lookup test | label=%1 | position=%2 | rawValue=%3 | actual=%4 | expected=%5 | match=%6", test.Get(0), testPosition, testValue, actualTier, test.Get(3), matches); testsLogged++; } CloseFile(testFile); if (testsLogged > 0) return; } } vector position = Vector(m_WorldWidth * 0.5, 0, m_WorldHeight * 0.5); int value; if (TryGetValueFlags(position, value)) PrintFormat("[SFL ARM COMPAT] Tier lookup test | position=%1 | rawValue=%2 | tier=%3", position, value, SFLCompatValueText(value)); else PrintFormat("[SFL ARM COMPAT] Tier lookup test FAILED | position=%1", position); } protected bool SFLCompatParseRun(string line, out int runValue, out int runCells, out string error) { runValue = 0; runCells = 0; error = ""; TStringArray run = new TStringArray; line.Split(",", run); if (run.Count() != 2 || !SFLCompatIsUnsignedDecimal(run.Get(0)) || !SFLCompatIsUnsignedDecimal(run.Get(1))) { error = "invalid tier RLE run line"; return false; } runValue = run.Get(0).ToInt(); runCells = run.Get(1).ToInt(); if (runValue < 0 || runValue > 255 || runCells <= 0) { error = "tier RLE run value/count is out of range"; return false; } return true; } protected int SFLCompatReadLine(out string line) { int charsRead = FGets(m_File, line); line = SFLCompatTrimLineEndings(line); return charsRead; } protected string SFLCompatTrimLineEndings(string line) { while (line.Length() > 0) { string lastCharacter = line.Get(line.Length() - 1); if (lastCharacter != "\r" && lastCharacter != "\n") break; line = line.Substring(0, line.Length() - 1); } return line; } protected bool SFLCompatIsUnsignedDecimal(string value) { if (value == "" || value.Length() > 10) return false; for (int i = 0; i < value.Length(); i++) { int character = value.Get(i).ToAscii(); if (character < 48 || character > 57) return false; } return true; } protected bool SFLCompatIsSha256(string value) { if (value.Length() != 64) return false; for (int i = 0; i < value.Length(); i++) { int character = value.Get(i).ToAscii(); bool isNumber = character >= 48 && character <= 57; bool isLowerHex = character >= 97 && character <= 102; if (!isNumber && !isLowerHex) return false; } return true; } protected string SFLCompatValueText(int value) { string result = ""; if ((value & AFR_ValueFlags.TIER_1) != 0) result = SFLCompatAppendValueName(result, "Tier1"); if ((value & AFR_ValueFlags.TIER_2) != 0) result = SFLCompatAppendValueName(result, "Tier2"); if ((value & AFR_ValueFlags.TIER_3) != 0) result = SFLCompatAppendValueName(result, "Tier3"); if ((value & AFR_ValueFlags.TIER_4) != 0) result = SFLCompatAppendValueName(result, "Tier4"); if ((value & AFR_ValueFlags.UNIQUE) != 0) result = SFLCompatAppendValueName(result, "Unique"); if (result == "") return ""; return result; } protected string SFLCompatAppendValueName(string current, string name) { if (current == "") return name; return current + " | " + name; } protected void SFLCompatEnterFallback(string reason) { if (m_SFLCompatState == SFL_COMPAT_STATE_FALLBACK) return; SFLCompatRemoveLoadStep(); m_SFLCompatState = SFL_COMPAT_STATE_FALLBACK; m_SFLCompatPendingCells = 0; if (m_ValuePages) { m_ValuePages.Clear(); delete m_ValuePages; } Fail("SFL ARM Compat v2: " + reason); PrintFormat("[SFL ARM COMPAT] Tier loader unavailable | reason=%1", reason); Print("[SFL ARM COMPAT] Tier loader unavailable; falling back to Tier1 compatibility mode"); } };