From 888cfe9239aa0d06acb310a1acafd6b4fc66aada Mon Sep 17 00:00:00 2001 From: Arseny Kapoulkine Date: Fri, 30 Aug 2024 13:17:35 -0700 Subject: [PATCH] gltfpack: Sanitize floats before writing them to JSON inf/nan are not valid in JSON syntax; while ideally we would not produce these values in the first place, it would make sense to have a last-resort check that outputs valid JSON regardless of the values. For +-inf we clamp them to max float, preserving the sign; for NaNs we choose to output max float for now since that value is still valid in JSON but looks sufficiently weird that it's obvious something happened during processing. --- gltf/json.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/gltf/json.cpp b/gltf/json.cpp index 92062d070..c46ef45a0 100644 --- a/gltf/json.cpp +++ b/gltf/json.cpp @@ -1,6 +1,8 @@ // This file is part of gltfpack; see gltfpack.h for version/license details #include "gltfpack.h" +#include +#include #include void comma(std::string& s) @@ -20,8 +22,12 @@ void append(std::string& s, size_t v) void append(std::string& s, float v) { + // sanitize +-inf to +-FLT_MAX and NaN to FLT_MAX + // it would be more consistent to use null for NaN but that makes JSON invalid, and 0 makes it hard to distinguish from valid values + float sv = fabsf(v) < FLT_MAX ? v : (v < 0 ? -FLT_MAX : FLT_MAX); + char buf[64]; - snprintf(buf, sizeof(buf), "%.9g", v); + snprintf(buf, sizeof(buf), "%.9g", sv); s += buf; }