Last active
July 1, 2024 05:30
-
-
Save zb-sj/43c7516ccc0ea64664e9e5290dd479f5 to your computer and use it in GitHub Desktop.
Extract .babylon materials to each json file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
FILE_PATH="*.babylon" | |
TEXTURE_OUT="./textures/" | |
JSON_OUT="./" | |
# Ensure FILE_PATH and TEXTURE_OUT are defined | |
if [[ -z "$FILE_PATH" || -z "$TEXTURE_OUT" ]]; then | |
echo "FILE_PATH and TEXTURE_OUT must be set." | |
exit 1 | |
fi | |
# Process each material | |
jq -r '.materials[] | .name' "$FILE_PATH" | while read -r material_name; do | |
# Extract all necessary data in one jq call | |
jq -r --arg name "$material_name" ' | |
.materials[] | select(.name==$name) | to_entries[] | | |
select(.value | type == "object") | | |
(.key | sub("Texture$"; "")) as $texture_type | | |
{key: $texture_type, value: .value} | | |
.value | to_entries[] | | |
select(.value | type == "string" and test("^data:image/(.*);base64,")) | | |
"\($texture_type) \(.value)"' "$FILE_PATH" | | |
while IFS=" " read -r texture_type base64String; do | |
# Process the base64String | |
extension=$(echo "$base64String" | sed -n 's/^data:image\/\([a-zA-Z]*\);base64,.*/\1/p') | |
if ! echo "$base64String" | sed 's/^data:image\/[a-zA-Z]*;base64,//' | base64 --decode > "${TEXTURE_OUT}${material_name}_${texture_type}.${extension}"; then | |
echo "Failed to decode and save base64 string for ${material_name}_${texture_type}.${extension}" | |
continue | |
fi | |
done | |
# Update the JSON | |
jq --arg name "$material_name" --argjson extmap '{"png":"png","jpeg":"jpg","jpg":"jpg"}' ' | |
.materials[] | select(.name==$name) | | |
walk(if type == "object" and has("base64String") then | |
.name = ($name + "_" + path(.)[-1] + "." + ($extmap[(.base64String | split(",")[0] | split("/")[1] | split(";")[0])] // "null")) | | |
.url = ($name + "_" + path(.)[-1] + "." + ($extmap[(.base64String | split(",")[0] | split("/")[1] | split(";")[0])] // "null")) | | |
del(.base64String) | |
elif type == "object" then | |
with_entries( | |
if (.key | test("Texture$"; "i")) and ((.value | type) == "object") then | |
(.key | sub("Texture$"; "")) as $texture_type | | |
.value.name = ($name + "_" + $texture_type) | | |
.value.url = ($name + "_" + $texture_type) | |
else | |
. | |
end | |
) | |
else | |
. | |
end | |
)' "$FILE_PATH" > "${JSON_OUT}${material_name}.json" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment