Spaces:
Sleeping
Sleeping
Download godot_android.py from Cnass/Godotmaker: direct link, hf CLI and curl.
- Browser
- Download file 14.8 kB
-
https://huggingface.co/spaces/Cnass/Godotmaker/resolve/main/godot_android.py
- Command line
-
hf download hf://spaces/Cnass/Godotmaker/godot_android.py
-
curl -L -o godot_android.py https://huggingface.co/spaces/Cnass/Godotmaker/resolve/main/godot_android.py
14.8 kB
| """Android performans profili: oyunu telefona göre hazırlar. | |
| Godot oyunları çoğu zaman yalnız masaüstü için dışa aktarılır. Telefonda üç şey | |
| yavaşlatır, bu modül üçünü de derleme sırasında düzeltir: | |
| 1. Dokular: masaüstü dışa aktarması VRAM dokularını yalnız S3TC/BPTC (BCn) | |
| olarak yazar (`.import` içinde `path.s3tc` / `path.bptc`). Telefon GPU'larının | |
| çoğu BCn okuyamaz; Godot da dokuyu yükleme anında işlemcide açar | |
| (ResourceFormatImporter "decomp_path"), sıkıştırmasız dört-sekiz kat VRAM'e koyar. | |
| Burada bloklar çözülüp ETC2/EAC'ye (her Android GPU'sunun desteklediği biçim) | |
| çevrilir ve `.import` satırı `path.etc2` olur. Bayt düzeni Godot 4.5 | |
| ResourceImporterTexture::_save_ctex ile aynıdır. | |
| 2. Paketleme: Gradle şablonu assets/ dosyalarını sıkıştırır; Godot editörü ise | |
| .ctex/.scn/.webp/.cfb/.pck'yi sıkıştırmadan koyar (export_plugin.cpp | |
| _should_compress_asset). Aynı liste build.gradle'a `noCompress` olarak eklenir; | |
| yalnız .ctex sıkıştırılır: bizim ETC2'ye çevirdiğimiz dokular (saydam/boş | |
| alanlar) deflate ile ~20 kat küçülüyor (Captive Lili APK'sı 1.4 GB → ~0.5 GB). | |
| 3. Proje ayarları: 2D oyunda OpenGL (gl_compatibility), `hdr_2d` kapalı; | |
| 3D oyunda Vulkan Mobil + düşük çözünürlük ölçeği ve pahalı efektler kısık. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| import struct | |
| from dataclasses import dataclass, field | |
| from pathlib import Path | |
| import godot_project as gpj | |
| # CompressedTexture2D: "GST2", sürüm, genişlik, yükseklik, bayraklar, mip sınırı, 3 ayrılmış | |
| # alan; ardından veri biçimi, uint16 en/boy, mip sayısı, Image::Format, veri. | |
| CTEX_HEADER = 36 | |
| DATA_FORMAT_IMAGE, DATA_FORMAT_PNG, DATA_FORMAT_WEBP = 0, 1, 2 | |
| # Image::Format (core/io/image.h, 4.0-4.7 aynı). | |
| DXT1, DXT5, RGTC_R, RGTC_RG, BPTC_RGBA = 17, 19, 20, 21, 22 | |
| RGB8, RGBA8 = 4, 5 | |
| ETC2_RGB8, ETC2_RGBA8 = 30, 31 | |
| # Bundan küçük kayıpsız dokular (arayüz, piksel sanatı) kayıpsız kalır: ETC2 blok izi orada göze batar, | |
| # kazanç da önemsiz. 512x512 RGBA8 = 1 MB görüntü belleği. | |
| PORTABLE_MIN_PIXELS = 512 * 512 | |
| PORTABLE_MAX_EDGE = 8192 # birçok telefon GPU'sunun en büyük doku kenarı | |
| # kaynak biçim → (texture2ddecoder çözücüsü, etcpak kodlayıcısı, hedef biçim). | |
| # Çözücüler BGRA verir, etcpak'ın ETC2 kodlayıcıları RGBA ister. RGTC (BC4/BC5, 3D normal ve | |
| # pürüzlülük haritaları) çevrilmez: etcpak'ın EAC kodlayıcısı yanlış kanal üretiyor; Godot | |
| # bunları telefonda kendisi açar. | |
| CONVERSIONS = { | |
| DXT1: ("decode_bc1", "compress_etc2_rgb", ETC2_RGB8), | |
| DXT5: ("decode_bc3", "compress_etc2_rgba", ETC2_RGBA8), | |
| BPTC_RGBA: ("decode_bc7", "compress_etc2_rgba", ETC2_RGBA8), | |
| } | |
| # Image::get_format_pixel_size / get_format_pixel_rshift: blok başına bayt = 16 * piksel / 2^shift. | |
| BITS_PER_PIXEL = {DXT1: 4, DXT5: 8, BPTC_RGBA: 8, ETC2_RGB8: 4, ETC2_RGBA8: 8} | |
| DESKTOP_FEATURES = ("s3tc", "bptc") | |
| MOBILE_FEATURES = ("etc2", "astc") | |
| _REMAP_LINE = re.compile(r'^path\.(s3tc|bptc)="(res://[^"]+)"\s*$', re.M) | |
| _PLAIN_PATH_LINE = re.compile(r'^path="(res://[^"]+\.ctex)"\s*$', re.M) | |
| # Godot editörünün Android dışa aktarmasında sıkıştırmadığı Godot'ya özgü uzantılar | |
| # (medya uzantılarını AGP zaten sıkıştırmaz); .ctex bilerek dışarıda (bkz. madde 2). | |
| NO_COMPRESS = [".webp", ".cfb", ".scn", ".pck"] | |
| RENDERERS = ("auto", "gl_compatibility", "mobile", "keep") | |
| # Sahne/kaynaklarda bu sınıflardan biri geçiyorsa oyun 3D sayılır. | |
| _3D_MARKERS = (b"Camera3D", b"MeshInstance3D", b"MultiMeshInstance3D", b"CSGShape3D", b"GridMap") | |
| _SCENE_SUFFIXES = (".tscn", ".scn", ".res", ".tres") | |
| class TextureError(Exception): | |
| pass | |
| class TextureReport: | |
| converted: int = 0 | |
| skipped: list[str] = field(default_factory=list) | |
| bytes_before: int = 0 | |
| bytes_after: int = 0 | |
| compressed: int = 0 # kayıpsız → ETC2 | |
| vram_saved: int = 0 | |
| def codecs_available() -> bool: | |
| try: | |
| import etcpak # noqa: F401 | |
| import texture2ddecoder # noqa: F401 | |
| except ImportError: | |
| return False | |
| return True | |
| def _level_sizes(width: int, height: int, mipmaps: int): | |
| """Image::_get_dst_image_size: her seviye 4x4 bloğa yuvarlanır, en küçük 1 px.""" | |
| w, h = width, height | |
| for _ in range(mipmaps + 1): | |
| yield (w + 3) // 4 * 4, (h + 3) // 4 * 4 | |
| w, h = max(1, w >> 1), max(1, h >> 1) | |
| def _swap_rb(buf: bytes) -> bytes: | |
| out = bytearray(buf) | |
| out[0::4], out[2::4] = buf[2::4], buf[0::4] | |
| return bytes(out) | |
| def convert_ctex(data: bytes) -> bytes: | |
| """BCn biçimli .ctex'i ETC2/EAC .ctex'e çevirir (başlık ve mip yapısı korunur).""" | |
| import etcpak | |
| import texture2ddecoder | |
| if len(data) < CTEX_HEADER + 16 or data[:4] != b"GST2": | |
| raise TextureError("GST2 başlığı yok") | |
| df, w, h, mipmaps, fmt = struct.unpack_from("<IHHII", data, CTEX_HEADER) | |
| if df != DATA_FORMAT_IMAGE: | |
| raise TextureError(f"veri biçimi {df} (VRAM görüntüsü değil)") | |
| if fmt in (RGTC_R, RGTC_RG): | |
| raise TextureError("kanal haritası (RGTC), telefonda Godot açar") | |
| if fmt not in CONVERSIONS: | |
| raise TextureError(f"desteklenmeyen biçim {fmt}") | |
| decoder, encoder, target = CONVERSIONS[fmt] | |
| decode, encode = getattr(texture2ddecoder, decoder), getattr(etcpak, encoder) | |
| bpp = BITS_PER_PIXEL[fmt] | |
| pos = CTEX_HEADER + 16 | |
| out = [data[:CTEX_HEADER], struct.pack("<IHHII", df, w, h, mipmaps, target)] | |
| for bw, bh in _level_sizes(w, h, mipmaps): | |
| size = bw * bh * bpp // 8 | |
| block = data[pos:pos + size] | |
| if len(block) != size: | |
| raise TextureError("veri yarım") | |
| pos += size | |
| bgra = decode(block, bw, bh) | |
| encoded = encode(_swap_rb(bgra), bw, bh) | |
| if len(encoded) != bw * bh * BITS_PER_PIXEL[target] // 8: | |
| raise TextureError("kodlayıcı beklenmeyen boyut verdi") | |
| out.append(encoded) | |
| return b"".join(out) | |
| def convert_portable_ctex(data: bytes) -> bytes: | |
| """Kayıpsız/kayıplı (WebP/PNG) büyük dokuyu ETC2'ye çevirir: telefonda RGBA8 yerine 4-8 bit/piksel. | |
| Godot 2D dokuları varsayılan olarak kayıpsız içe aktarır; motor bunları GPU'ya sıkıştırmadan | |
| (32 bit/piksel) yükler. Başlıktaki mantıksal boyut korunur (texture_set_size_override). | |
| """ | |
| import io | |
| import etcpak | |
| from PIL import Image | |
| if len(data) < CTEX_HEADER + 20 or data[:4] != b"GST2": | |
| raise TextureError("GST2 başlığı yok") | |
| df, w, h, mipmaps, fmt = struct.unpack_from("<IHHII", data, CTEX_HEADER) | |
| if df not in (DATA_FORMAT_PNG, DATA_FORMAT_WEBP): | |
| raise TextureError(f"veri biçimi {df} (gömülü PNG/WebP değil)") | |
| if fmt not in (RGB8, RGBA8): | |
| raise TextureError(f"desteklenmeyen biçim {fmt}") | |
| if mipmaps: | |
| raise TextureError("mipmap'li gömülü doku") | |
| if w * h < PORTABLE_MIN_PIXELS: | |
| raise TextureError("küçük doku (kayıpsız kalır)") | |
| if max(w, h) > PORTABLE_MAX_EDGE: | |
| # Telefonda yüklenemez; katman (riaslink.gd _genis_dokulari_bol) çalışırken karelere keser | |
| # ve bunun için gömülü PNG/WebP'yi okur. | |
| raise TextureError("8192'den geniş doku (kayıpsız kalır)") | |
| size = struct.unpack_from("<I", data, CTEX_HEADER + 16)[0] | |
| blob = data[CTEX_HEADER + 20:CTEX_HEADER + 20 + size] | |
| if blob[:4] == b"PNG ": # Godot'nun png_packer öneki (WebP'de yok) | |
| blob = blob[4:] | |
| try: | |
| img = Image.open(io.BytesIO(blob)) | |
| img.load() | |
| except Exception as exc: # bozuk/okunamayan gömülü görüntü | |
| raise TextureError(f"görüntü açılamadı: {exc}") from exc | |
| img = img.convert("RGBA") | |
| opaque = img.getextrema()[3][0] == 255 | |
| bw, bh = (w + 3) // 4 * 4, (h + 3) // 4 * 4 | |
| if (bw, bh) != img.size: | |
| # Godot'nun etcpak sıkıştırıcısı da 4'ün katına büyütür (kenar doldurmaz, ölçekler). | |
| img = img.resize((bw, bh), Image.BILINEAR) | |
| raw = img.tobytes() | |
| target = ETC2_RGB8 if opaque else ETC2_RGBA8 | |
| encoded = (etcpak.compress_etc2_rgb if opaque else etcpak.compress_etc2_rgba)(raw, bw, bh) | |
| if len(encoded) != bw * bh * BITS_PER_PIXEL[target] // 8: | |
| raise TextureError("kodlayıcı beklenmeyen boyut verdi") | |
| return data[:CTEX_HEADER] + struct.pack("<IHHII", DATA_FORMAT_IMAGE, bw, bh, 0, target) + encoded | |
| def _vram_size(data: bytes) -> int: | |
| """Dokunun GPU'da kapladığı yaklaşık bayt (yalnız mipmap'siz tek seviye).""" | |
| _, w, h, _, fmt = struct.unpack_from("<IHHII", data, CTEX_HEADER) | |
| return w * h * {RGB8: 24, RGBA8: 32}.get(fmt, BITS_PER_PIXEL.get(fmt, 32)) // 8 | |
| def _compress_portable(assets: Path, imp_text: str, report: TextureReport) -> None: | |
| m = _PLAIN_PATH_LINE.search(imp_text) | |
| if not m: | |
| return | |
| src = assets / m.group(1)[len("res://"):] | |
| if not src.is_file(): | |
| return | |
| data = src.read_bytes() | |
| try: | |
| new = convert_portable_ctex(data) | |
| except TextureError: | |
| return # küçük/uygunsuz doku: olduğu gibi kalır, hata değil | |
| src.write_bytes(new) | |
| report.compressed += 1 | |
| report.vram_saved += _vram_size(data) - _vram_size(new) | |
| def convert_textures(assets: Path, log, portable: bool = True) -> TextureReport: | |
| """Masaüstü biçimli (BCn) dokuları ETC2'ye çevirir; portable ise büyük kayıpsız dokuları da.""" | |
| report = TextureReport() | |
| for imp in sorted(assets.rglob("*.import")): | |
| text = imp.read_text("utf-8", "replace") | |
| if 'type="CompressedTexture2D"' not in text or any(f"path.{f}=" in text for f in MOBILE_FEATURES): | |
| continue | |
| m = _REMAP_LINE.search(text) | |
| if not m: | |
| if portable: | |
| _compress_portable(assets, text, report) | |
| continue | |
| rel = m.group(2)[len("res://"):] | |
| src = assets / rel | |
| if not src.is_file(): | |
| report.skipped.append(f"{rel} (dosya yok)") | |
| continue | |
| data = src.read_bytes() | |
| try: | |
| new = convert_ctex(data) | |
| except TextureError as exc: | |
| report.skipped.append(f"{rel} ({exc})") | |
| continue | |
| new_rel = re.sub(r"\.(s3tc|bptc)\.ctex$", ".etc2.ctex", rel) | |
| if new_rel == rel: | |
| new_rel = rel[:-len(".ctex")] + ".etc2.ctex" | |
| (assets / new_rel).write_bytes(new) | |
| src.unlink() | |
| text = text[:m.start()] + f'path.etc2="res://{new_rel}"' + text[m.end():] | |
| text = re.sub(r'"imported_formats": \[[^\]]*\]', '"imported_formats": ["etc2_astc"]', text) | |
| imp.write_text(text, "utf-8") | |
| report.converted += 1 | |
| report.bytes_before += len(data) | |
| report.bytes_after += len(new) | |
| return report | |
| def disable_asset_compression(build_gradle: Path) -> bool: | |
| """aaptOptions bloğuna noCompress ekler; blok bulunamazsa False.""" | |
| text = build_gradle.read_text("utf-8") | |
| if "noCompress" in text: | |
| return True | |
| line = "noCompress " + ", ".join(f"'{e}'" for e in NO_COMPRESS) | |
| new, n = re.subn(r"^(\s*)(aaptOptions|androidResources)\s*\{\s*\n", | |
| lambda m: f"{m.group(0)}{m.group(1)} {line}\n", text, count=1, flags=re.M) | |
| if not n: | |
| return False | |
| build_gradle.write_text(new, "utf-8") | |
| return True | |
| _REMAP_PATH = re.compile(rb'^path="res://([^"]+)"', re.M) | |
| def _addon_exports(assets: Path) -> set[str]: | |
| """Eklenti sahnelerinin dışa aktarılmış kopyaları (.godot/exported/...): addons/*.remap hedefleri.""" | |
| out = set() | |
| addons = assets / "addons" | |
| for r in addons.rglob("*.remap") if addons.is_dir() else (): | |
| m = _REMAP_PATH.search(r.read_bytes()) | |
| if m: | |
| out.add(m.group(1).decode("utf-8", "replace")) | |
| return out | |
| def is_3d(assets: Path) -> bool: | |
| """Eklenti (addons/) örnekleri dışındaki sahnelerde 3D düğüm var mı.""" | |
| skip = _addon_exports(assets) | |
| for p in assets.rglob("*"): | |
| if p.suffix not in _SCENE_SUFFIXES and not p.name.endswith(".remap"): | |
| continue | |
| rel = p.relative_to(assets).as_posix() | |
| if rel.startswith("addons/") or rel in skip or not p.is_file(): | |
| continue | |
| data = p.read_bytes() | |
| if any(mk in data for mk in _3D_MARKERS): | |
| return True | |
| return False | |
| def choose_renderer(choice: str, three_d: bool) -> str: | |
| if choice not in RENDERERS: | |
| raise ValueError(f"Bilinmeyen görüntü motoru: {choice}") | |
| if choice == "auto": | |
| return "mobile" if three_d else "gl_compatibility" | |
| return choice | |
| def apply_profile(project: gpj.ProjectBinary, renderer: str, three_d: bool) -> list[str]: | |
| """Mobil proje ayarlarını yazar; günlüğe yazılacak kısa notları döndürür.""" | |
| notes = [] | |
| if renderer != "keep": | |
| for key in ("rendering/renderer/rendering_method", "rendering/renderer/rendering_method.mobile"): | |
| project.set_string(key, renderer) | |
| notes.append("görüntü motoru " + ("OpenGL (uyumluluk)" if renderer == "gl_compatibility" else "Vulkan Mobil")) | |
| if renderer == "mobile": | |
| project.set_bool("rendering/rendering_device/fallback_to_opengl3", True) | |
| if project.get_value("rendering/viewport/hdr_2d"): | |
| project.set_bool("rendering/viewport/hdr_2d", False) | |
| notes.append("hdr_2d kapalı") | |
| msaa_2d = project.get_value("rendering/anti_aliasing/quality/msaa_2d") | |
| if isinstance(msaa_2d, int) and msaa_2d > 0: | |
| project.set_int("rendering/anti_aliasing/quality/msaa_2d", 0) | |
| notes.append("2D kenar yumuşatma (MSAA) kapalı") | |
| if three_d: | |
| scale = project.get_value("rendering/scaling_3d/scale") | |
| if not isinstance(scale, float) or scale > 0.75: | |
| project.set_float("rendering/scaling_3d/scale", 0.75) | |
| for key in ("rendering/anti_aliasing/quality/msaa_3d", "rendering/anti_aliasing/quality/screen_space_aa", | |
| "rendering/environment/ssao/quality", "rendering/environment/ssil/quality", | |
| "rendering/environment/screen_space_reflection/roughness_quality", | |
| "rendering/lights_and_shadows/directional_shadow/soft_shadow_filter_quality", | |
| "rendering/lights_and_shadows/positional_shadow/soft_shadow_filter_quality"): | |
| project.set_int(key, 0) | |
| for key in ("rendering/lights_and_shadows/directional_shadow/size", | |
| "rendering/lights_and_shadows/positional_shadow/atlas_size"): | |
| size = project.get_value(key) | |
| if not isinstance(size, int) or size > 2048: | |
| project.set_int(key, 2048) | |
| notes.append("3D: çözünürlük %75, kenar yumuşatma/SSAO/SSR kapalı, gölge ≤2048") | |
| return notes | |