diff --git a/.gitattributes b/.gitattributes index 67d9e76..ae1243c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -6,3 +6,7 @@ *.py text eol=lf *.ps1 text eol=crlf *.glb filter=lfs diff=lfs merge=lfs -text +*.stl filter=lfs diff=lfs merge=lfs -text +*.blend filter=lfs diff=lfs merge=lfs -text + +/Demon_v0.19/reviews/infernal_v01/*.gif filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore index ca647bb..d68941f 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,7 @@ **/*.bak **/__pycache__/ **/*.pyc +**/*.blend1 /tools/godot/ /tools/templates/ diff --git a/Demon_v0.19/reviews/infernal_v01/README.md b/Demon_v0.19/reviews/infernal_v01/README.md new file mode 100644 index 0000000..aebe1b3 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/README.md @@ -0,0 +1,78 @@ +# INFERNAL — STL-образец на согласование + +Основа — предоставленная пользователем `infernal.zip`; исходная сетка сохранена +без изменений в `tools/model_sources/infernal.stl`. Покраска по переданной схеме: +красная кожа, чёрные волосы, корсет, сапоги, рога, крылья и хвост. STL не содержал +цветов, UV или скелета: материалы и UV подготовлены заново. + +Модель пока **не подключена** к главной героине и помощницам. Игровой +`art/succubus/succubus_v02.glb` сохранён; сначала согласовывается этот образец. + +## Содержимое + +- `infernal_game.glb`: 45 493 вершины / 90 801 треугольник тела, 166 костей, + Idle / Walk / Whip; дополнительный хлыст со старыми анимированными формами. +- `infernal_basecolor.png`, `infernal_normal.png`, `infernal_orm.png`: 4096×4096, + материалы и детали исходного скульпта; всё также встроено в GLB. +- `walking.gif`: 6 секунд, ходьба, поворот и остановка. +- `turntable.gif`: 5 секунд, полный оборот, лёгкие движения крыльев и хвоста. +- `whip.gif`: 4 секунды, перенесённый удар; радиус шнура увеличен на 8 мм + в координатах модели, сохранены старые волны хлыста. +- `face.gif`: 3 секунды, лицо крупным планом. +- `manifest.json`, `validation.json`: фактические параметры и результаты QA. +- `review.tscn`: отдельная сцена Godot для просмотра и записи кадров. +- `tools/model_sources/infernal_game.blend`: редактируемая игровая сетка, + скелет, анимации и упакованные текстуры. Исходный STL и схема покраски рядом. + +## Исправления + +Подставка срезана на 0,150 м исходной нормализованной модели, подошвы закрыты. +Контакты рук с одеждой отделены и очищены. Соединённые при печати ботинки +разрезаны и закрыты по отдельности; у каждой стопы собственная жёсткая привязка. +Плечи, локти и запястья подогнаны к скульпту. Idle, Walk и Whip перенесены +с предыдущего скелета относительно его позы Idle. + +В образце используется прежняя походка с коротким шагом, раздельными дорожками +для обуви, фиксацией опорной стопы и разворотом до 22°. Крылья покачиваются +без активных взмахов; хвост и крылья сохраняют слабое движение в покое. + +Границы корсета, фигурного подола, воротника и сапог обведены по рельефу +исходной сетки, включая переданную пользователем оранжевую обводку +`tools/model_sources/approved_paint_boundary.png`. Контуры хранятся в +`tools/infernal_seams.py`; проекция учитывает глубину и скрытую изнанку складок. +Крупные планы — paint-front/hem/boots/back.png. + +Исправлены координаты глаз/губ и граница воротника. Открытые руки используют +отдельный материал кожи, чтобы при близких поверхностях в них не запекалась +чёрная одежда. Карта нормалей сохраняет нейтральную нормаль для пустых лучей. + +## Проверки + +Godot 4.3: импорт PASS; `review_tests.gd` PASS — два масштаба, четыре скорости, +30/60 fps, поворот на 90°, остановка, контакт с полом. Ошибка IK <0,000003 м, +разворот стоп ≤22°, углы крыльев <0,05 рад, хвоста <0,013 рад. + +Blender: `validate_infernal.py` PASS — три клипа, нормализованные веса, +конечные координаты, отсутствие подставки, защищённый материал рук, три карты +4K. Проверяются кадры клипов с шагом 4; максимальный прирост ребра: Idle +0,00234 м, Walk 0,03596 м, Whip 0,06717 м. Результаты — в validation.json. + +GIF сняты с настоящей 3D-модели в Godot, 24 fps. Это образец для визуального +согласования покраски, пропорций и движений, а не смена модели в игровой сцене. + +## Воспроизведение + +Из корня репозитория, Blender 5.0.1 / Godot 4.3 / FFmpeg: + +```powershell +& 'C:/Program Files/Blender Foundation/Blender 5.0/blender.exe' --background --python-exit-code 1 --python tools/build_infernal.py -- --bake +& 'C:/Program Files/Blender Foundation/Blender 5.0/blender.exe' --background --python-exit-code 1 --python tools/validate_infernal.py +& $godot --headless --editor --path Demon_v0.19 --import --quit +& $godot --path Demon_v0.19 --script res://reviews/infernal_v01/review_tests.gd +& $godot --path Demon_v0.19 --resolution 1280x900 res://reviews/infernal_v01/review.tscn +& $python tools/encode_infernal_review.py --ffmpeg $ffmpeg +``` + +`finish_infernal.py` позволяет повторить покраску из локального checkpoint, +созданного build_infernal.py в игнорируемом captures. Для чистого клона +использовать полный build с `--bake`. Большие STL/BLEND/GLB хранятся в Git LFS. diff --git a/Demon_v0.19/reviews/infernal_v01/face.gif b/Demon_v0.19/reviews/infernal_v01/face.gif new file mode 100644 index 0000000..5b293c9 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/face.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:320be193a158b7a24bba44f36700236e92227abda30b5d0378b2adc3fef7f3a9 +size 16109660 diff --git a/Demon_v0.19/reviews/infernal_v01/infernal_basecolor.png b/Demon_v0.19/reviews/infernal_v01/infernal_basecolor.png new file mode 100644 index 0000000..4d2bc2d Binary files /dev/null and b/Demon_v0.19/reviews/infernal_v01/infernal_basecolor.png differ diff --git a/Demon_v0.19/reviews/infernal_v01/infernal_basecolor.png.import b/Demon_v0.19/reviews/infernal_v01/infernal_basecolor.png.import new file mode 100644 index 0000000..c06c0ed --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/infernal_basecolor.png.import @@ -0,0 +1,34 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://h11gmfuc3yid" +path="res://.godot/imported/infernal_basecolor.png-350d9c43584265a4600dd1c2f5d415d2.ctex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://reviews/infernal_v01/infernal_basecolor.png" +dest_files=["res://.godot/imported/infernal_basecolor.png-350d9c43584265a4600dd1c2f5d415d2.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=false +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 diff --git a/Demon_v0.19/reviews/infernal_v01/infernal_gait.gd b/Demon_v0.19/reviews/infernal_v01/infernal_gait.gd new file mode 100644 index 0000000..e3eaca2 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/infernal_gait.gd @@ -0,0 +1,17 @@ +extends "res://reviews/heels_v01/review_gait.gd" + +var secondary_time=0.0 +func _init(): + stride_min=.95;stride_max=1.15;track_width=.09;swing_height=.11 +func ground_height(f):return actor.get_parent().global_position.y+f.rest.y*actor.global_basis.get_scale().y+.004 + +func update(dt): + super.update(dt) + secondary_time+=dt + # Small delayed motion at rest and after each step, rooted at the back. + var tail_angle=sin(secondary_time*.95)*.012+sin(phase*TAU-.9)*.024*walk_weight + rotate_world("Tail",actor.global_basis.y,tail_angle) + rotate_world("Tail",actor.global_basis.x,sin(secondary_time*.7)*.006) + for side in ["L","R"]: + var sign_x=1.0 if side=="L" else -1.0 + rotate_world("Wing."+side,actor.global_basis.y,sign_x*sin(secondary_time*.8)*.010) diff --git a/Demon_v0.19/reviews/infernal_v01/infernal_game.glb b/Demon_v0.19/reviews/infernal_v01/infernal_game.glb new file mode 100644 index 0000000..a79a12f --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/infernal_game.glb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c677685dac4a327e00fe69e657745fcfe7899007b7d933db38df9c6464ac7c90 +size 19143820 diff --git a/Demon_v0.19/reviews/infernal_v01/infernal_game.glb.import b/Demon_v0.19/reviews/infernal_v01/infernal_game.glb.import new file mode 100644 index 0000000..def4014 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/infernal_game.glb.import @@ -0,0 +1,36 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://dnwqqu4x1yixr" +path="res://.godot/imported/infernal_game.glb-6448dfcc6ac429989645a3e78a7b85df.scn" + +[deps] + +source_file="res://reviews/infernal_v01/infernal_game.glb" +dest_files=["res://.godot/imported/infernal_game.glb-6448dfcc6ac429989645a3e78a7b85df.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +nodes/import_as_skeleton_bones=false +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +animation/import_rest_as_RESET=false +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 diff --git a/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_basecolor.png b/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_basecolor.png new file mode 100644 index 0000000..4d2bc2d Binary files /dev/null and b/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_basecolor.png differ diff --git a/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_basecolor.png.import b/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_basecolor.png.import new file mode 100644 index 0000000..c12f36a --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_basecolor.png.import @@ -0,0 +1,37 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://c2y84kbnraj7y" +path="res://.godot/imported/infernal_game_infernal_basecolor.png-34717ecb9e7b45d91a837b43ba01b8bd.ctex" +metadata={ +"vram_texture": false +} +generator_parameters={ +"md5": "ec06996f35d03b5dff4ef74214143a93" +} + +[deps] + +source_file="res://reviews/infernal_v01/infernal_game_infernal_basecolor.png" +dest_files=["res://.godot/imported/infernal_game_infernal_basecolor.png-34717ecb9e7b45d91a837b43ba01b8bd.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=true +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 diff --git a/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_normal.png b/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_normal.png new file mode 100644 index 0000000..286c7d6 Binary files /dev/null and b/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_normal.png differ diff --git a/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_normal.png.import b/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_normal.png.import new file mode 100644 index 0000000..aa169f8 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_normal.png.import @@ -0,0 +1,37 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://iafy125bmvbe" +path="res://.godot/imported/infernal_game_infernal_normal.png-c2c19f73bb1372ea42fa568379419c76.ctex" +metadata={ +"vram_texture": false +} +generator_parameters={ +"md5": "1fd5b6ab6d56b8a97cd3149923cfd9b1" +} + +[deps] + +source_file="res://reviews/infernal_v01/infernal_game_infernal_normal.png" +dest_files=["res://.godot/imported/infernal_game_infernal_normal.png-c2c19f73bb1372ea42fa568379419c76.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=true +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 diff --git a/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_orm.png b/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_orm.png new file mode 100644 index 0000000..d3ef95a Binary files /dev/null and b/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_orm.png differ diff --git a/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_orm.png.import b/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_orm.png.import new file mode 100644 index 0000000..88ff843 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/infernal_game_infernal_orm.png.import @@ -0,0 +1,37 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://8x13rikdlqpq" +path="res://.godot/imported/infernal_game_infernal_orm.png-e6dc5617699cdf651dbb650ff9bbb2c5.ctex" +metadata={ +"vram_texture": false +} +generator_parameters={ +"md5": "e403e04738838a82a634d99ad78bcb53" +} + +[deps] + +source_file="res://reviews/infernal_v01/infernal_game_infernal_orm.png" +dest_files=["res://.godot/imported/infernal_game_infernal_orm.png-e6dc5617699cdf651dbb650ff9bbb2c5.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=true +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 diff --git a/Demon_v0.19/reviews/infernal_v01/infernal_normal.png b/Demon_v0.19/reviews/infernal_v01/infernal_normal.png new file mode 100644 index 0000000..286c7d6 Binary files /dev/null and b/Demon_v0.19/reviews/infernal_v01/infernal_normal.png differ diff --git a/Demon_v0.19/reviews/infernal_v01/infernal_normal.png.import b/Demon_v0.19/reviews/infernal_v01/infernal_normal.png.import new file mode 100644 index 0000000..4472c50 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/infernal_normal.png.import @@ -0,0 +1,34 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://i1dvwa6ay77q" +path="res://.godot/imported/infernal_normal.png-7a0a668238a6788bfc68b37824ded72f.ctex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://reviews/infernal_v01/infernal_normal.png" +dest_files=["res://.godot/imported/infernal_normal.png-7a0a668238a6788bfc68b37824ded72f.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=false +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 diff --git a/Demon_v0.19/reviews/infernal_v01/infernal_orm.png b/Demon_v0.19/reviews/infernal_v01/infernal_orm.png new file mode 100644 index 0000000..d3ef95a Binary files /dev/null and b/Demon_v0.19/reviews/infernal_v01/infernal_orm.png differ diff --git a/Demon_v0.19/reviews/infernal_v01/infernal_orm.png.import b/Demon_v0.19/reviews/infernal_v01/infernal_orm.png.import new file mode 100644 index 0000000..3308fc4 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/infernal_orm.png.import @@ -0,0 +1,34 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://sbsfb7x1x01q" +path="res://.godot/imported/infernal_orm.png-8c10a8117721c2a05d861c9d6b1776fd.ctex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://reviews/infernal_v01/infernal_orm.png" +dest_files=["res://.godot/imported/infernal_orm.png-8c10a8117721c2a05d861c9d6b1776fd.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=false +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 diff --git a/Demon_v0.19/reviews/infernal_v01/manifest.json b/Demon_v0.19/reviews/infernal_v01/manifest.json new file mode 100644 index 0000000..4ba0827 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/manifest.json @@ -0,0 +1,20 @@ +{ + "source_triangles": 1569740, + "source_after_pedestal_cut": 1402834, + "game_vertices": 45493, + "game_triangles": 90801, + "bones": 166, + "clips": { + "Idle": 73, + "Walk": 33, + "Whip": 65 + }, + "pedestal_removed": true, + "cut_height": 0.15, + "textures_4k": true, + "animated_whip": true, + "facial_paint": "aligned to sculpt: eyes z1.889, lips z1.817", + "paint_boundary_reference": "tools/model_sources/approved_paint_boundary.png", + "whip_radius_added_m": 0.008, + "approval_status": "awaiting_visual_approval" +} \ No newline at end of file diff --git a/Demon_v0.19/reviews/infernal_v01/paint-back.png b/Demon_v0.19/reviews/infernal_v01/paint-back.png new file mode 100644 index 0000000..70ae48e Binary files /dev/null and b/Demon_v0.19/reviews/infernal_v01/paint-back.png differ diff --git a/Demon_v0.19/reviews/infernal_v01/paint-back.png.import b/Demon_v0.19/reviews/infernal_v01/paint-back.png.import new file mode 100644 index 0000000..8eea4d4 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/paint-back.png.import @@ -0,0 +1,34 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://blesb51kvusas" +path="res://.godot/imported/paint-back.png-a9ecbf6915faebfe58909fd12c6363ce.ctex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://reviews/infernal_v01/paint-back.png" +dest_files=["res://.godot/imported/paint-back.png-a9ecbf6915faebfe58909fd12c6363ce.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=false +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 diff --git a/Demon_v0.19/reviews/infernal_v01/paint-boots.png b/Demon_v0.19/reviews/infernal_v01/paint-boots.png new file mode 100644 index 0000000..a967050 Binary files /dev/null and b/Demon_v0.19/reviews/infernal_v01/paint-boots.png differ diff --git a/Demon_v0.19/reviews/infernal_v01/paint-boots.png.import b/Demon_v0.19/reviews/infernal_v01/paint-boots.png.import new file mode 100644 index 0000000..3617a86 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/paint-boots.png.import @@ -0,0 +1,34 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://06tag3t032oa" +path="res://.godot/imported/paint-boots.png-6d85a81d17c643f0e201c560d04ba238.ctex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://reviews/infernal_v01/paint-boots.png" +dest_files=["res://.godot/imported/paint-boots.png-6d85a81d17c643f0e201c560d04ba238.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=false +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 diff --git a/Demon_v0.19/reviews/infernal_v01/paint-face.png b/Demon_v0.19/reviews/infernal_v01/paint-face.png new file mode 100644 index 0000000..ea911b5 Binary files /dev/null and b/Demon_v0.19/reviews/infernal_v01/paint-face.png differ diff --git a/Demon_v0.19/reviews/infernal_v01/paint-face.png.import b/Demon_v0.19/reviews/infernal_v01/paint-face.png.import new file mode 100644 index 0000000..a7698f2 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/paint-face.png.import @@ -0,0 +1,34 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://cim7cnd0p0uh4" +path="res://.godot/imported/paint-face.png-144ee864f8e0242f5f2ebb3984669832.ctex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://reviews/infernal_v01/paint-face.png" +dest_files=["res://.godot/imported/paint-face.png-144ee864f8e0242f5f2ebb3984669832.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=false +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 diff --git a/Demon_v0.19/reviews/infernal_v01/paint-front.png b/Demon_v0.19/reviews/infernal_v01/paint-front.png new file mode 100644 index 0000000..67c11d2 Binary files /dev/null and b/Demon_v0.19/reviews/infernal_v01/paint-front.png differ diff --git a/Demon_v0.19/reviews/infernal_v01/paint-front.png.import b/Demon_v0.19/reviews/infernal_v01/paint-front.png.import new file mode 100644 index 0000000..285e46a --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/paint-front.png.import @@ -0,0 +1,34 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://dwn1rr45e0eqt" +path="res://.godot/imported/paint-front.png-69e7570935f7f102d4b9601a605accad.ctex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://reviews/infernal_v01/paint-front.png" +dest_files=["res://.godot/imported/paint-front.png-69e7570935f7f102d4b9601a605accad.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=false +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 diff --git a/Demon_v0.19/reviews/infernal_v01/paint-hem.png b/Demon_v0.19/reviews/infernal_v01/paint-hem.png new file mode 100644 index 0000000..aa55816 Binary files /dev/null and b/Demon_v0.19/reviews/infernal_v01/paint-hem.png differ diff --git a/Demon_v0.19/reviews/infernal_v01/paint-hem.png.import b/Demon_v0.19/reviews/infernal_v01/paint-hem.png.import new file mode 100644 index 0000000..d6c1d7f --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/paint-hem.png.import @@ -0,0 +1,34 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://ch4ecfxchsjc6" +path="res://.godot/imported/paint-hem.png-4928b89f31d8671d9797b385ca440e97.ctex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://reviews/infernal_v01/paint-hem.png" +dest_files=["res://.godot/imported/paint-hem.png-4928b89f31d8671d9797b385ca440e97.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=false +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 diff --git a/Demon_v0.19/reviews/infernal_v01/review.gd b/Demon_v0.19/reviews/infernal_v01/review.gd new file mode 100644 index 0000000..25c679e --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/review.gd @@ -0,0 +1,87 @@ +extends Node3D +var paused=false +var actor +var carrier +var camera: Camera3D +var heading: Label +var folder="res://captures/infernal" +var max_error=0.0 +var max_yaw=0.0 + +func _ready():call_deferred("run") + +func setup_studio(): + var world=WorldEnvironment.new();add_child(world);world.environment=Environment.new() + world.environment.background_mode=Environment.BG_COLOR;world.environment.background_color=Color("242932") + world.environment.ambient_light_source=Environment.AMBIENT_SOURCE_COLOR;world.environment.ambient_light_color=Color("d1d9e5");world.environment.ambient_light_energy=.7 + world.environment.tonemap_mode=Environment.TONE_MAPPER_FILMIC + for at in [Vector3(-3,5,5),Vector3(4,3,2),Vector3(0,4,-4)]: + var light=OmniLight3D.new();add_child(light);light.position=at;light.light_energy=3.5;light.omni_range=30;light.shadow_enabled=true + var floor_node=MeshInstance3D.new();add_child(floor_node);floor_node.mesh=BoxMesh.new();floor_node.mesh.size=Vector3(80,.08,80);floor_node.position=Vector3(0,-.045,10) + var material=StandardMaterial3D.new();material.albedo_color=Color("454b55");material.roughness=.85;floor_node.material_override=material + camera=Camera3D.new();add_child(camera);camera.projection=Camera3D.PROJECTION_ORTHOGONAL;camera.current=true + var layer=CanvasLayer.new();add_child(layer);heading=Label.new();layer.add_child(heading);heading.position=Vector2(30,22);heading.add_theme_font_size_override("font_size",24) + carrier=Node3D.new();add_child(carrier) + actor=preload("res://succubus_actor.gd").new(preload("res://reviews/infernal_v01/infernal_game.glb"));carrier.add_child(actor);actor.rotation=Vector3.ZERO + actor.gait=preload("res://reviews/infernal_v01/infernal_gait.gd").new();actor.configure(self);actor.set_process(false) + +func advance(direction,speed): + carrier.position+=direction*speed/24.0 + if direction.length_squared()>.1:actor.rotation.y=lerp_angle(actor.rotation.y,atan2(direction.x,direction.z),10.0/24) + actor._process(1.0/24) + for foot in actor.gait.feet: + max_error=maxf(max_error,actor.gait.point("foot."+foot.side).distance_to(foot.target)) + max_yaw=maxf(max_yaw,absf(wrapf(foot.yaw-actor.global_rotation.y,-PI,PI))) + +func reset(): + actor.restore_animation_pose();carrier.position=Vector3.ZERO;actor.rotation=Vector3.ZERO;actor.striking=false;actor.animator.play(actor.clips["Idle"],0.0,1.0);actor.animator.seek(0,true);actor.remember_animation_pose();actor.reset_gait() + +func save_frame(sequence,frame): + await RenderingServer.frame_post_draw + assert(get_viewport().get_texture().get_image().save_png(folder+"/"+sequence+"/%03d.png"%frame)==OK) + +func run(): + for sequence in ["full","outfit","action","portrait"]:DirAccess.make_dir_recursive_absolute(folder+"/"+sequence) + setup_studio();await get_tree().process_frame + if "--qa-stills" in OS.get_cmdline_user_args(): + DirAccess.make_dir_recursive_absolute(folder+"/still") + for index in range(4): + advance(Vector3.ZERO,0) + var angle=index*PI/2;var focus=Vector3(0,1.25,0);camera.size=3.0;camera.position=focus+Vector3(sin(angle)*5,.25,cos(angle)*5);camera.look_at(focus) + heading.text="ПОКРАСКА · ПРОВЕРКА СТОРОН";await save_frame("still",index) + var focus=Vector3(0,2.1,0);camera.size=.92;camera.position=focus+Vector3(0,.07,5);camera.look_at(focus) + heading.text="ЛИЦО · ПРОВЕРКА ПОКРАСКИ";await save_frame("still",4) + actor.strike(1.8) + for frame in range(24):advance(Vector3.ZERO,0) + focus=Vector3(0,1.25,0);camera.size=3.15;camera.position=focus+Vector3(2,.6,7);camera.look_at(focus) + heading.text="WHIP · ПРОВЕРКА";await save_frame("still",5) + reset() + for detail in [[6,1.56,1.15,0.0,"КОРСЕТ И ВОРОТНИК · ПО ЛИНИЯМ СКУЛЬПТА"],[7,1.32,.70,0.0,"НИЖНЯЯ КРОМКА КОРСЕТА"],[8,.32,.80,0.0,"САПОГИ · КРАЙ ПО ОБОДКУ"],[9,1.56,1.15,PI,"КОРСЕТ · ВИД СЗАДИ"]]: + advance(Vector3.ZERO,0) + var detail_focus=Vector3(0,detail[1],0);camera.size=detail[2];camera.position=detail_focus+Vector3(sin(detail[3])*5,.02,cos(detail[3])*5);camera.look_at(detail_focus) + heading.text=detail[4];await save_frame("still",detail[0]) + get_tree().quit();return + heading.text="INFERNAL / STL · ХОДЬБА, ПОВОРОТ И ОСТАНОВКА" + for frame in range(144): + var direction=Vector3.BACK if frame<72 else Vector3(.7,0,.7).normalized() + advance(direction,2.5 if frame<110 else 0) + var focus=carrier.position+Vector3(0,1.25,0);camera.size=3.15;camera.position=focus+Vector3(2.0,.7,7);camera.look_at(focus) + await save_frame("full",frame) + reset();heading.text="ПОКРАСКА · КРАСНАЯ КОЖА / ЧЁРНЫЙ КОМПЛЕКТ" + for frame in range(120): + advance(Vector3.ZERO,0) + var focus=Vector3(0,1.25,0);var angle=TAU*frame/120;camera.size=3.0;camera.position=focus+Vector3(sin(angle)*5,.25,cos(angle)*5);camera.look_at(focus) + await save_frame("outfit",frame) + reset();heading.text="ПЕРЕНОС АНИМАЦИИ · WHIP" + for frame in range(96): + if frame==12:actor.strike(1.8) + advance(Vector3.ZERO,0) + var focus=Vector3(0,1.25,0);camera.size=3.15;camera.position=focus+Vector3(2,.6,7);camera.look_at(focus) + await save_frame("action",frame) + reset();heading.text="ЛИЦО · КРУПНЫЙ ПЛАН" + for frame in range(72): + advance(Vector3.ZERO,0) + var focus=Vector3(0,2.10,0);var angle=sin(TAU*frame/72)*.22;camera.size=.92;camera.position=focus+Vector3(sin(angle)*5,.07,cos(angle)*5);camera.look_at(focus) + await save_frame("portrait",frame) + print("INFERNAL REVIEW METRICS ",JSON.stringify({"max_ik_error":max_error,"max_ankle_twist_degrees":rad_to_deg(max_yaw)})) + get_tree().quit() diff --git a/Demon_v0.19/reviews/infernal_v01/review.tscn b/Demon_v0.19/reviews/infernal_v01/review.tscn new file mode 100644 index 0000000..7047194 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/review.tscn @@ -0,0 +1,4 @@ +[gd_scene load_steps=2 format=3] +[ext_resource type="Script" path="res://reviews/infernal_v01/review.gd" id="1"] +[node name="InfernalApprovalStudio" type="Node3D"] +script = ExtResource("1") diff --git a/Demon_v0.19/reviews/infernal_v01/review_tests.gd b/Demon_v0.19/reviews/infernal_v01/review_tests.gd new file mode 100644 index 0000000..ae5b77c --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/review_tests.gd @@ -0,0 +1,37 @@ +extends SceneTree +var failures=[] +func _initialize():call_deferred("run") +func check(ok,label): + if not ok and not label in failures:failures.append(label);push_error("INFERNAL REVIEW QA: "+label) +func run(): + var max_error=0.0;var max_twist=0.0;var max_wing=0.0;var max_tail=0.0 + for scale_y in [1.0,.82]: + var carrier=Node3D.new();root.add_child(carrier) + var actor=preload("res://succubus_actor.gd").new(preload("res://reviews/infernal_v01/infernal_game.glb"));carrier.add_child(actor);actor.scale=Vector3.ONE*scale_y;actor.rotation=Vector3.ZERO + check(actor.clips.has("Idle") and actor.clips.has("Walk") and actor.clips.has("Whip"),"all three transferred animations imported") + actor.gait=preload("res://reviews/infernal_v01/infernal_gait.gd").new();actor.configure(self);actor.set_process(false) + for speed in [1.0,2.5,3.3,5.775]: + for fps in [30,60]: + actor.restore_animation_pose();carrier.position=Vector3.ZERO;actor.rotation=Vector3.ZERO;actor.reset_gait() + for frame in range(fps*3): + var direction=Vector3.BACK if frame=actor.gait.ground_height(f)-.003,"ankles above floor") + var wi=actor.skeleton.find_bone("Wing.L");var wing=actor.skeleton.get_bone_pose_rotation(wi) + max_wing=maxf(max_wing,wing.angle_to(actor.animation_pose[wi].basis.get_rotation_quaternion())) + for frame in range(fps):actor._process(1.0/fps) + var tail_id=actor.skeleton.find_bone("Tail") + max_tail=maxf(max_tail,actor.skeleton.get_bone_pose_rotation(tail_id).angle_to(actor.animation_pose[tail_id].basis.get_rotation_quaternion())) + for f in actor.gait.feet:check(f.grounded,"stopping settles both shoes") + check(actor.gait.track_width>.065,"separate paths keep wide heels apart") + carrier.queue_free();await process_frame + check(max_tail>.001 and max_tail<.06,"tail moves gently with a fixed root") + check(max_error<.005,"IK reaches both shoes at both scales and four speeds") + check(max_twist<=deg_to_rad(22.01),"ankle heading never twists more than 22 degrees") + check(max_wing>.01 and max_wing<.10,"wings sway gently instead of active flapping") + print("INFERNAL REVIEW METRICS ",JSON.stringify({"max_ik_error":max_error,"max_heading_twist_degrees":rad_to_deg(max_twist),"max_wing_pose_angle":max_wing,"max_tail_pose_angle":max_tail,"failures":failures})) + if failures.is_empty():print("ALL INFERNAL REVIEW TESTS PASSED: heroine/helper scales, four speeds, two frame rates, right-angle turns, stop, reach and ankle heading") + quit(0 if failures.is_empty() else 1) diff --git a/Demon_v0.19/reviews/infernal_v01/turntable.gif b/Demon_v0.19/reviews/infernal_v01/turntable.gif new file mode 100644 index 0000000..be5a329 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/turntable.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1cdf965787d9fe5c90fad7c31b7c0bb75cd66b24b262aabd3db6107a101d6c88 +size 8942650 diff --git a/Demon_v0.19/reviews/infernal_v01/validation.json b/Demon_v0.19/reviews/infernal_v01/validation.json new file mode 100644 index 0000000..aebf05a --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/validation.json @@ -0,0 +1,28 @@ +{ + "status": "PASS", + "mesh_vertices": 45493, + "mesh_triangles": 90801, + "bones": 166, + "floor_min_z": -3.110424222541042e-05, + "pedestal_removed": true, + "skin_material_protected": true, + "pbr_maps": "4096x4096 basecolor / normal / ORM", + "clips": { + "Idle": { + "frames": 73, + "max_vertex_travel_m": 0.05229, + "max_edge_growth_m": 0.00234 + }, + "Walk": { + "frames": 33, + "max_vertex_travel_m": 0.63687, + "max_edge_growth_m": 0.03596 + }, + "Whip": { + "frames": 65, + "max_vertex_travel_m": 0.85563, + "max_edge_growth_m": 0.06717 + } + }, + "glb_bytes": 19143820 +} \ No newline at end of file diff --git a/Demon_v0.19/reviews/infernal_v01/walking.gif b/Demon_v0.19/reviews/infernal_v01/walking.gif new file mode 100644 index 0000000..c6af825 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/walking.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b13e54ede5308b6cdc39ea8dae99eb9d5f269adc8b58c68f8e64ec355642fa09 +size 11184633 diff --git a/Demon_v0.19/reviews/infernal_v01/whip.gif b/Demon_v0.19/reviews/infernal_v01/whip.gif new file mode 100644 index 0000000..ef41fb7 --- /dev/null +++ b/Demon_v0.19/reviews/infernal_v01/whip.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6fd2b2e1f941c4b5a8ce62022c56b60a4ad6c9ecb6fb0ebaebfddf1236d2db3 +size 4163584 diff --git a/HANDOFF.md b/HANDOFF.md index a7f78a6..35413ba 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -35,48 +35,45 @@ `Missing code in response; could not read Username`. Локальный коммит сохранён, вступление ещё не опубликовано в origin. -- **Текущая задача (в работе):** пользователь остановил реконструкцию по - изображениям и передал `C:/Users/jaros/Downloads/infernal.zip` с единственной - `infernal .stl`. Исходник извлечён в `tools/model_sources/infernal.stl` - (1 569 740 треугольников). Новый ориентир покраски: красная кожа, чёрные волосы, - корсет, сапоги и крылья; картинка с этой же статуэткой. Нужно убрать подставку, - перенести прежний скелет/анимации и подправить их. Запрос GIF на согласование - по-прежнему действует. Предыдущие картинки и красный комплект ниже больше - не являются текущим вариантом. -- Инструменты STL: `tools/build_infernal.py` (Blender 5), `inspect_infernal.py`, - `probe_infernal.py`, `probe_infernal_rig.py`, `render_infernal_check.py`. - Модель нормализована до 2,2 м по полному STL, подставка срезана на z=.150 м, - подошвы закрыты и сдвинуты к z=0. После среза 1 402 834 треугольника; рабочая - сетка 45 378 вершин / 91 184 треугольника. Готовятся 4K basecolor/normal/ORM. -- Старый `succubus_v02.glb` импортируется в Blender как источник 166 костей и - Idle (73 кадра), Walk (33), Whip (65), 24 fps. Новые rest bones подогнаны - к STL по исходному Idle frame 1. Ключи переносятся по world-space delta - относительно этого Idle, чтобы не опустить руки второй раз из старой A-позы. - Веса тела переносятся от исходной позированной поверхности через KDTree; - крылья/хвост отделяются по геодезической связности поверхности. Это ещё - проверяется: первые прямоугольные маски ошибочно захватывали внутренние - перепонки в запястья, что растягивало их при Whip. Последний build уточняет - цилиндрические arm-seeds и wing-seeds; результат надо пересмотреть. -- Текущие файлы STL-образца: `reviews/infernal_v01/infernal_game.glb`, manifest, - `infernal_gait.gd`, `review.gd`, `review.tscn`. Editable source: - `tools/model_sources/infernal_game.blend`. Пока без baked textures; для - финальной сборки: Blender `--background --python tools/build_infernal.py -- --bake`. - Пакет в игре ещё НЕ включён, по умолчанию по-прежнему старый succubus_v02. - В Godot preview ходьбы IK уже давал ошибку <0,000002 м, но были артефакты - весов, поэтому этот ранний preview НЕ выдавать как готовый результат. -- Служебный `captures/.gdignore` необходим: внутри captures лежит большой - `infernal-inspect/source_inspection.blend`; без .gdignore Godot зависал на его - автоматическом Blender-импорте. Рендеры и инспекционные файлы не игровые ассеты. - При финальном commit добавить только этот marker принудительно, не captures. - -- Новый актуальный ориентир пользователя после красного комплекта: три вида - суккубы (спереди, сзади и сбоку), чёрное бикини и броня/ботфорты на каблуках, - длинный высокий чёрный хвост волос, длинные рога, низкие коричневые крылья - с кожистой неровной перепонкой и тонкий шипастый хвост. Запрошены максимальная - точность, реализм и качество текстур. У пользователя нет исходного 3D-файла - и ссылки на автора; это реконструкция по изображениям, точное совпадение - исходной сетки и текстур не подтверждено. Этот референс заменяет красный - комплект ниже. Исправление стоп и слабое покачивание крыльев сохраняются. +- **STL INFERNAL: образец готов, согласование внешнего вида ожидается.** + Коммит образца сохранён локально. Push этой задачи также заблокирован + авторизацией GCM/OAuth: `Missing code in response; could not read Username`. + В origin новые изменения ещё не опубликованы. + `reviews/infernal_v01/` содержит GLB, три карты 4K, GIF ходьбы/оборота/удара/лица, + manifest, validation и отдельную сцену просмотра. В рабочую игру НЕ включён: + по умолчанию по-прежнему `art/succubus/succubus_v02.glb`. +- Сохранены пользовательские исходники `tools/model_sources/infernal.stl` + (1 569 740 треугольников; байты сверены с infernal.zip), color_reference.png, + SOURCES.json, редактируемый infernal_game.blend. Новая игровая сетка: + 45 493 вершины / 90 801 треугольник, 166 костей; подставка удалена, подошвы + закрыты. Печатные контакты рук и соединение ботинок разделены. Idle (73), + Walk (33), Whip (65 кадров) перенесены со старого скелета, 24 fps. +- Покраска: красная кожа, чёрный комплект, волосы, крылья, рога и хвост. + По замечанию пользователя исправлено попадание чёрного цвета на открытую + кожу: отдельный материал рук, непрерывные маски, уменьшены лучи запекания. + По дополнительной просьбе пользователя контуры перерисованы по реальным + швам скульпта: чашки, фигурный подол, воротник, ободки сапог. Присланная + оранжевая обводка сохранена как tools/model_sources/approved_paint_boundary.png. + Проекция по глубине отделяет ткань от руки за ней; скрытые складки получают + окраску по соседней поверхности. Контуры — infernal_seams.py. + Глаза/губы выровнены по скульпту; воротник заканчивается ниже подбородка. + Плеть сохранена со старыми morph-анимациями, добавлен радиус шнура 8 мм. +- У крыльев и хвоста лёгкое вторичное движение в покое и при ходьбе. Походка + образца: короткий шаг, раздельные дорожки стоп, IK, ограничение разворота 22°. + Результаты Godot: PASS, ошибка IK <0,000003 м; два масштаба, четыре скорости, + 30/60 fps, поворот/остановка, мягкие движения крыльев и хвоста. +- `tools/validate_infernal.py` PASS: три клипа с шагом 4 кадра, нормализованные + веса, конечные координаты, отсутствие подставки, защищённый материал кожи, + три карты 4096²; max edge growth Idle .00234 / Walk .03596 / Whip .06717 м. + GIF сняты заново с окончательного GLB в Godot; дальнейшая правка должна + повторять запись, а не использовать кадры от прежних вариантов. +- Сборка: tools/build_infernal.py -- --bake, модули infernal_skinning/surface/ + facepaint/bake/whip/seams.py. Локально finish_infernal.py повторяет покраску из + checkpoint в captures. encode_infernal_review.py кодирует GIF. Полные команды + в reviews/infernal_v01/README.md. Исходники STL/BLEND/GLB через LFS. +- captures/.gdignore исключает технические большие BLEND и кадры из импорта. + Перечисленные ниже модели красного комплекта и реконструкция по картинкам + являются историческими вариантами; их заменил запрос на пользовательский STL. - Подготовлен **образец на согласование**, ещё не включённый в игровую сцену: `Demon_v0.19/reviews/heels_v01`. Пользователь запросил каблуки и исправление @@ -84,8 +81,7 @@ красный кожаный корсет с воротником/кольцами, ремнями, задней шнуровкой, наплечниками-крыльями и большие крылья с лёгким покачиванием при ходьбе. `walking.gif`, `boots.gif`, `outfit.gif` показывают настоящий 3D-образец. - Ожидается согласование внешнего вида и движения перед подключением героине - и помощницам. Исходный `art/succubus/succubus_v02.glb` не менялся. + Этот исторический образец заменён текущим STL; в игровую сцену не включён. Исходный `art/succubus/succubus_v02.glb` не менялся. - В образце стопы перепривязаны: сустав поднят на 8 см в координатах модели, исправлены inverse bind matrices и трансляции клипов; подошва жёсткая, отдельно от каблука, не деформируется пальцами. Предварительная походка: diff --git a/tools/build_infernal.py b/tools/build_infernal.py new file mode 100644 index 0000000..9d9f99b --- /dev/null +++ b/tools/build_infernal.py @@ -0,0 +1,323 @@ +import sys +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parent)) +"""Adapt the supplied sculpture, retain its detail and retarget the existing rig. +Run with Blender 5: blender --background --python tools/build_infernal.py [-- --bake] +""" +import bpy,bmesh,math,json,sys,heapq +import numpy as np +from pathlib import Path +from mathutils import Vector,Matrix +from mathutils.kdtree import KDTree + +ROOT=Path(__file__).resolve().parent.parent +OUT=ROOT/'Demon_v0.19/reviews/infernal_v01';OUT.mkdir(parents=True,exist_ok=True) +QA=ROOT/'Demon_v0.19/captures/infernal';QA.mkdir(parents=True,exist_ok=True) +CUT=.150 +BAKE='--bake' in sys.argv +bpy.ops.wm.read_factory_settings(use_empty=True) +bpy.context.preferences.view.use_translate_new_dataname=False +scene=bpy.context.scene;scene.render.fps=24 + +def active(obj): + bpy.ops.object.select_all(action='DESELECT');obj.select_set(True);bpy.context.view_layer.objects.active=obj +def log(*args):print('INFERNAL',*args,flush=True) +def color_role(p,hint=None): + x,y,z=p;z+=CUT;a=abs(x) + if hint in [4,5]:return 2 if z<1.025 and a>.245 else 0 + # The outer membranes and spars are behind the exposed arms. + wing=(a>.39 and z>.54) or (a>.215 and y>.102 and z>1.12) or (a>.22 and z>1.72) + tail=(z<1.27 and y>.085 and a<.40 and (z<.70 or a>.17 or y>.185)) + hair=(a<.19 and z>1.968-(.85 if x<0 else .55)*a) or (a<.17 and y>.075 and z>1.30) or (.0651.52) + horn=z>1.96 + if hint in [1,2,3] or wing or tail:return 3 + if hair or horn:return 2 + if z<.615:return 1 + top=1.545+.080*min(a/.12,1);bottom=1.10+.13*min(a/.19,1) + width=float(np.interp(z,[1.1,1.25,1.4,1.55,1.63],[.18,.205,.17,.185,.17])) + if a.245 and z<1.025:return 2 + return 0 + +PALETTE=[('Crimson skin',(.42,.013,.024),.47,0),('Black leather corset and boots',(.012,.016,.019),.30,.12),('Black hair and horns',(.009,.010,.014),.41,.02),('Dark bat wings and armoured tail',(.018,.019,.023),.52,.04),('Amber eyes',(.32,.18,.02),.25,.10),('Dark red lips',(.045,.002,.008),.33,0)] +materials=[] +for name,color,rough,metal in PALETTE: + m=bpy.data.materials.new(name);m.diffuse_color=(*color,1);m.use_nodes=True + shader=next(n for n in m.node_tree.nodes if n.type=='BSDF_PRINCIPLED');shader.inputs['Base Color'].default_value=(*color,1);shader.inputs['Roughness'].default_value=rough;shader.inputs['Metallic'].default_value=metal + materials.append(m) + +# Preserve the supplied geometry as the bake source, cutting only the pedestal. +bpy.ops.wm.stl_import(filepath=str(ROOT/'tools/model_sources/infernal.stl')) +high=bpy.context.object;high.name='Infernal_High_Source_No_Pedestal';high.scale*=2.2/high.dimensions.z +bpy.context.view_layer.update();corners=[high.matrix_world@Vector(c) for c in high.bound_box] +lo=Vector(tuple(min(p[i] for p in corners) for i in range(3)));hi=Vector(tuple(max(p[i] for p in corners) for i in range(3))) +high.location-=Vector(((lo.x+hi.x)/2,(lo.y+hi.y)/2,lo.z));active(high);bpy.ops.object.transform_apply(location=True,rotation=True,scale=True) +before=len(high.data.polygons);bm=bmesh.new();bm.from_mesh(high.data) +result=bmesh.ops.bisect_plane(bm,geom=list(bm.verts)+list(bm.edges)+list(bm.faces),plane_co=(0,0,CUT),plane_no=(0,0,1),clear_inner=True,dist=.000001) +boundary=[e for e in result['geom_cut'] if isinstance(e,bmesh.types.BMEdge) and e.is_boundary and all(abs(v.co.z-CUT)<.00001 for v in e.verts)] +if boundary:bmesh.ops.holes_fill(bm,edges=boundary,sides=0) +for v in bm.verts:v.co.z-=CUT +bmesh.ops.triangulate(bm,faces=list(bm.faces));bm.to_mesh(high.data);bm.free();high.data.update() +for m in materials:high.data.materials.append(m) +for p in high.data.polygons:p.use_smooth=True;p.material_index=color_role(p.center) +log('pedestal removed',before,'->',len(high.data.polygons),'triangles') + +# Real-time topology; the fine sculpt is retained in the baked normal texture. +low=high.copy();low.data=high.data.copy();scene.collection.objects.link(low);low.name='Infernal_Game_Mesh' +active(low);modifier=low.modifiers.new('Game topology','DECIMATE');modifier.ratio=.065;modifier.use_collapse_triangulate=True +bpy.ops.object.modifier_apply(modifier=modifier.name) +for p in low.data.polygons:p.use_smooth=True;p.material_index=color_role(p.center) +log('game topology',len(low.data.vertices),'vertices',len(low.data.polygons),'triangles') + +# Use surface connectivity to distinguish the tail and wing tips from nearby +# hands and boots. A spatial box alone stretches the sculpture when arms move. +coords=np.empty(len(low.data.vertices)*3,dtype=np.float64);low.data.vertices.foreach_get('co',coords);coords=coords.reshape(-1,3) +graph=[[] for _ in coords] +for edge in low.data.edges: + a,b=edge.vertices;length=float(np.linalg.norm(coords[a]-coords[b]));graph[a].append((b,length));graph[b].append((a,length)) +tail_path=np.array([(0,.21,1.25),(.20,.21,1.05),(.33,.17,.85),(.36,.11,.65),(.30,.12,.43),(.12,.15,.26),(-.13,.15,.25),(-.30,.13,.37),(-.33,.12,.52),(-.23,.10,.60)]) +arm_path=np.array([(.150,.015,1.70),(.170,.025,1.57),(.190,.035,1.40),(.235,.005,1.25),(.257,-.015,1.10),(.270,-.035,1.00)]) +def path_distance(p,path): + result=np.inf + for start,end in zip(path[:-1],path[1:]): + segment=end-start;t=np.clip(np.dot(p-start,segment)/np.dot(segment,segment),0,1);result=min(result,float(np.linalg.norm(p-(start+t*segment)))) + return result +seeds=[];owner=np.full(len(coords),-1,dtype=np.int8);distance=np.full(len(coords),np.inf) +for i,(x,y,z) in enumerate(coords): + zo=z+CUT;a=abs(x);label=-1 + arm_distance=path_distance(np.array([a,y,zo]),arm_path) + if (a<.105 and y<.08 and 1.051.75) or (a<.14 and y<.07 and zo<1.08):label=0 + if 1.12.130):label=0 + if .980 else 5 + if a>.50 and zo>.65:label=1 if x>0 else 2 + if a>.23 and zo>1.33 and y>.135:label=1 if x>0 else 2 + if a>.32 and zo>1.15 and y>.12:label=1 if x>0 else 2 + p=np.array([x,y,zo]);tail_distance=path_distance(p,tail_path) + if tail_distance<.028 and y>.075 and zo<1.27:label=3 + if label>=0:owner[i]=label;distance[i]=0;heapq.heappush(seeds,(0.,i,label)) +while seeds: + d,i,label=heapq.heappop(seeds) + if d>distance[i]:continue + for j,length in graph[i]: + nd=d+length + if nd.155 and .78.001] + if not weights:continue + p=body.matrix_world@evaluated_mesh.vertices[i].co;total=sum(w for _,w in weights);at=Vector((0,0,0)) + for name,w in weights:at+=(transforms[name]@p)*(w/total) + samples.append(at);sample_weights.append(weights) +evaluated.to_mesh_clear();tree=KDTree(len(samples)) +for i,p in enumerate(samples):tree.insert(p,i) +tree.balance();log('skin transfer samples',len(samples)) +def arm_name(name):return any(key in name for key in ['upperarm','lowerarm','wrist','finger','metacarpal']) +part_trees={} +for part in ['core','L','R']: + ids=[] + for i,weights in enumerate(sample_weights): + amount=sum(w for name,w in weights if arm_name(name) and (part=='core' or name.endswith('.'+part))) + if (part=='core' and amount<.01) or (part!='core' and amount>.4):ids.append(i) + kd=KDTree(len(ids)) + for i in ids:kd.insert(samples[i],i) + kd.balance();part_trees[part]=kd +for name in names:low.vertex_groups.new(name=name) +for vertex in low.data.vertices: + x,y,z=vertex.co;zo=z+CUT;a=abs(x);weights={} + label=int(owner[vertex.index]) + arm=label in [4,5] + if label in [1,2]: + wing_weight=float(np.clip((a-.16)/.16,0,1));weights={'Wing.L' if label==1 else 'Wing.R':wing_weight,'spine02':1-wing_weight} + elif label==3: + tail_weight=float(np.clip((Vector((x,y,z))-Vector((0,.17,1.09))).length/.16,0,1));weights={'Tail':tail_weight,'spine05':1-tail_weight} + elif z<.15:weights={'foot.L' if x>0 else 'foot.R':1.0} + elif arm and zo<1.12:weights={'wrist.L' if x>0 else 'wrist.R':1.0} + else: + shoulder=.130 else 'R') if arm else 'core'] + for _,index,distance in kd.find_n(vertex.co,4): + factor=1/max(.0001,distance)**2 + for name,w in sample_weights[index]: + if not shoulder and not arm and arm_name(name):continue + if not shoulder and arm and not (arm_name(name) or 'clavicle' in name):continue + if z<.95 and abs(x)>.025 and (name.endswith('.L') if x<0 else name.endswith('.R')):continue + weights[name]=weights.get(name,0)+w*factor + if y>.10 and zo>1.45 and a<.17: + blend=float(np.clip((zo-1.45)/.45,.25,1));weights={'head':blend,'spine02':1-blend} + pairs=sorted(weights.items(),key=lambda p:-p[1])[:4];total=sum(w for _,w in pairs) + for name,w in pairs:low.vertex_groups[name].add([vertex.index],w/total,'REPLACE') +# Smooth weights on connected surface regions without smearing hands into clothes. +weights_array=np.zeros((len(coords),len(names)),dtype=np.float32) +name_index={name:i for i,name in enumerate(names)} +for vertex in low.data.vertices: + for group in vertex.groups:weights_array[vertex.index,group.group]=group.weight +edges=np.array([tuple(e.vertices) for e in low.data.edges],dtype=np.int32) +edges=edges[owner[edges[:,0]]==owner[edges[:,1]]] +first=np.concatenate((edges[:,0],edges[:,1]));second=np.concatenate((edges[:,1],edges[:,0])) +counts=np.maximum(np.bincount(first,minlength=len(coords)),1) +for iteration in range(6): + average=np.zeros_like(weights_array) + for column in range(len(names)): + average[:,column]=np.bincount(first,weights=weights_array[second,column],minlength=len(coords))/counts + weights_array=weights_array*.45+average*.55 +shoulder_seams={} +for index,point in enumerate(coords): + if 1.481:weights_array[indices]=weights_array[indices].mean(axis=0) +for vertex in low.data.vertices: + weights=weights_array[vertex.index];indices=np.argsort(weights)[-4:];total=float(weights[indices].sum()) + for group in list(vertex.groups):low.vertex_groups[group.group].remove([vertex.index]) + for index in indices: + if weights[index]>.00001:low.vertex_groups[int(index)].add([vertex.index],float(weights[index])/total,'REPLACE') +from infernal_skinning import refine_weights +refine_weights(low) +log('weights smoothed with semantic boundaries') +modifier=low.modifiers.new('Transferred skeleton','ARMATURE');modifier.object=rig;low.parent=rig + +# Retarget world-space animation deltas relative to the old Idle bind pose. +rig.animation_data_create() +for clip,frames in sampled.items(): + action=bpy.data.actions.new('Infernal / '+clip);rig.animation_data.action=action + for f,frame in enumerate(frames,1): + desired={} + for name in names: + bone=rig.data.bones[name];parent=bone.parent + head=(desired[parent.name]@(rest[parent.name].inverted()@rest[name]).translation) if parent else rest[name].translation+(frame[name].translation-base[name].translation) + q=frame[name].to_quaternion()@base[name].to_quaternion().inverted()@rest[name].to_quaternion() + matrix=Matrix.LocRotScale(head,q,Vector((1,1,1)));desired[name]=matrix + kwargs={'matrix':matrix,'matrix_local':rest[name],'invert':True} + if parent:kwargs.update(parent_matrix=desired[parent.name],parent_matrix_local=rest[parent.name]) + basis=bone.convert_local_to_pose(**kwargs);pb=rig.pose.bones[name];pb.rotation_mode='QUATERNION';pb.rotation_quaternion=basis.to_quaternion();pb.location=basis.translation + pb.keyframe_insert('rotation_quaternion',frame=f,group=name);pb.keyframe_insert('location',frame=f,group=name) + rig.animation_data.action=None;track=rig.animation_data.nla_tracks.new();track.name=clip;strip=track.strips.new(clip,1,action);strip.frame_end=len(frames) + track.mute=True +log('retargeted',len(names),'bones') + +bpy.data.orphans_purge(do_recursive=True) +bpy.context.preferences.filepaths.save_version=0 +bpy.ops.wm.save_as_mainfile(filepath=str(QA/'retarget_checkpoint.blend')) + +if BAKE: + from infernal_bake import bake + bake(scene,high,low,materials,PALETTE,OUT,log) + +from infernal_whip import transfer_whip +whip=transfer_whip(scene,source,rig) + +# Export only the new game mesh and retargeted rig; leave the old asset intact. +for track in rig.animation_data.nla_tracks:track.mute=False +rig.animation_data.action=None;scene.frame_set(1) +for bone in rig.pose.bones:bone.matrix_basis.identity() +active(low);rig.select_set(True) +if whip:whip.select_set(True) +bpy.ops.export_scene.gltf(filepath=str(OUT/'infernal_game.glb'),export_format='GLB',use_selection=True,export_animations=True,export_animation_mode='NLA_TRACKS',export_nla_strips=True,export_force_sampling=True,export_frame_range=False,export_skins=True,export_materials='EXPORT',export_yup=True) +report={'source_triangles':before,'source_after_pedestal_cut':len(high.data.polygons),'game_vertices':len(low.data.vertices),'game_triangles':len(low.data.polygons),'bones':len(names),'clips':{k:len(v) for k,v in sampled.items()},'pedestal_removed':True,'cut_height':CUT,'textures_4k':BAKE} +report.update(paint_boundary_reference='tools/model_sources/approved_paint_boundary.png',whip_radius_added_m=.008,approval_status='awaiting_visual_approval') +(OUT/'manifest.json').write_text(json.dumps(report,indent=2));log('GAME ASSET READY',json.dumps(report)) +# Keep an editable optimized source without copying the entire high-poly statue. +for obj in list(scene.objects): + if obj not in [rig,low,whip]:bpy.data.objects.remove(obj,do_unlink=True) +bpy.data.orphans_purge(do_recursive=True) +bpy.context.preferences.filepaths.save_version=0 +bpy.ops.wm.save_as_mainfile(filepath=str(ROOT/'tools/model_sources/infernal_game.blend')) diff --git a/tools/encode_infernal_review.py b/tools/encode_infernal_review.py new file mode 100644 index 0000000..05578ec --- /dev/null +++ b/tools/encode_infernal_review.py @@ -0,0 +1,8 @@ +"""Encode actual Godot captures for STL model approval.""" +from pathlib import Path +import argparse,subprocess +parser=argparse.ArgumentParser();parser.add_argument('--ffmpeg',required=True);args=parser.parse_args() +r=Path(__file__).resolve().parent.parent;project=r/'Demon_v0.19';out=project/'reviews/infernal_v01' +for sequence,count,name in [('full',144,'walking'),('outfit',120,'turntable'),('action',96,'whip'),('portrait',72,'face')]: + subprocess.run([args.ffmpeg,'-hide_banner','-loglevel','error','-y','-framerate','24','-i',str(project/'captures/infernal'/sequence/'%03d.png'),'-filter_complex','[0:v]scale=1000:-1:flags=lanczos,split[a][b];[a]palettegen=max_colors=192[p];[b][p]paletteuse=dither=sierra2_4a','-frames:v',str(count),'-loop','0',str(out/(name+'.gif'))],check=True) + print(name,count,'frames',flush=True) diff --git a/tools/finish_infernal.py b/tools/finish_infernal.py new file mode 100644 index 0000000..a54ed8d --- /dev/null +++ b/tools/finish_infernal.py @@ -0,0 +1,40 @@ +"""Finish paint from the rig checkpoint without repeating geometry conversion.""" +import sys,json,bpy +from pathlib import Path +from mathutils import Matrix +sys.path.insert(0,str(Path(__file__).resolve().parent)) +from infernal_bake import bake +from infernal_skinning import refine_weights +from infernal_whip import transfer_whip +r=Path(__file__).resolve().parent.parent;out=r/'Demon_v0.19/reviews/infernal_v01';qa=r/'Demon_v0.19/captures/infernal' +bpy.ops.wm.open_mainfile(filepath=str(qa/'retarget_checkpoint.blend')) +scene=bpy.context.scene;low=bpy.data.objects['Infernal_Game_Mesh'];rig=bpy.data.objects['INFERNAL_RIG'];high=bpy.data.objects['Infernal_High_Source_No_Pedestal'] +source=next(o for o in scene.objects if o.type=='ARMATURE' and o!=rig) +materials=list(high.data.materials);palette=[(m.name,tuple(m.diffuse_color[:3]),next(n for n in m.node_tree.nodes if n.type=='BSDF_PRINCIPLED').inputs['Roughness'].default_value,next(n for n in m.node_tree.nodes if n.type=='BSDF_PRINCIPLED').inputs['Metallic'].default_value) for m in materials] +def log(*args):print('INFERNAL',*args,flush=True) +refine_weights(low) +# Keep exposed arms red; the hair mask must not paint forearms black. +from mathutils.kdtree import KDTree +kd=KDTree(len(low.data.vertices)) +for vertex in low.data.vertices:kd.insert(vertex.co,vertex.index) +kd.balance();regions=low.data.attributes['SemanticRegion'].data +for face in high.data.polygons: + _,index,_=kd.find(face.center) + if regions[index].value in [4,5]:face.material_index=2 if face.center.z+.15<1.025 and abs(face.center.x)>.245 else 0 +bake(scene,high,low,materials,palette,out,log) +whip=transfer_whip(scene,source,rig) +for track in rig.animation_data.nla_tracks:track.mute=False +rig.animation_data.action=None;scene.frame_set(1) +for bone in rig.pose.bones:bone.matrix_basis=Matrix.Identity(4) +bpy.ops.object.select_all(action='DESELECT');low.select_set(True);rig.select_set(True) +if whip:whip.select_set(True) +bpy.context.view_layer.objects.active=low +bpy.ops.export_scene.gltf(filepath=str(out/'infernal_game.glb'),export_format='GLB',use_selection=True,export_animations=True,export_animation_mode='NLA_TRACKS',export_nla_strips=True,export_force_sampling=True,export_frame_range=False,export_skins=True,export_materials='EXPORT',export_yup=True) +report=json.loads((out/'manifest.json').read_text());report.update(textures_4k=True,animated_whip=whip is not None,facial_paint='aligned to sculpt: eyes z1.889, lips z1.817',game_vertices=len(low.data.vertices),game_triangles=len(low.data.polygons)) +report.update(paint_boundary_reference='tools/model_sources/approved_paint_boundary.png',whip_radius_added_m=.008,approval_status='awaiting_visual_approval') +(out/'manifest.json').write_text(json.dumps(report,indent=2));log('FINISHED',report) +for obj in list(scene.objects): + if obj not in [rig,low,whip]:bpy.data.objects.remove(obj,do_unlink=True) +bpy.data.orphans_purge(do_recursive=True) +bpy.context.preferences.filepaths.save_version=0 +bpy.ops.wm.save_as_mainfile(filepath=str(r/'tools/model_sources/infernal_game.blend')) diff --git a/tools/infernal_bake.py b/tools/infernal_bake.py new file mode 100644 index 0000000..be6eeec --- /dev/null +++ b/tools/infernal_bake.py @@ -0,0 +1,73 @@ +import bpy,math,numpy as np +from mathutils import Matrix + +def active(obj): + bpy.ops.object.select_all(action="DESELECT");obj.select_set(True);bpy.context.view_layer.objects.active=obj + +def bake(scene,high,low,materials,palette,out,log): + rig=low.parent + from infernal_surface import prepare_surface + materials=prepare_surface(high,low) + # Bake colour, sculpt detail and material response into actual 4K maps. + for o in [o for o in scene.objects if o not in [high,low]]:o.hide_render=True + high.hide_render=False;low.hide_render=False + scene.render.engine='CYCLES';scene.cycles.samples=8 + try: + preferences=bpy.context.preferences.addons['cycles'].preferences;preferences.compute_device_type='OPTIX';preferences.get_devices() + for device in preferences.devices:device.use=device.type!='CPU' + scene.cycles.device='GPU' + except Exception as error:log('CPU bake fallback',str(error)) + active(low);bpy.ops.object.mode_set(mode='EDIT');bpy.ops.mesh.select_all(action='SELECT');bpy.ops.uv.smart_project(angle_limit=math.radians(66),island_margin=.003);bpy.ops.object.mode_set(mode='OBJECT') + final=bpy.data.materials.new('Infernal 4K PBR');final.use_nodes=True;low.data.materials.clear();low.data.materials.append(final) + for p in low.data.polygons:p.material_index=0 + scene.render.bake.use_selected_to_active=True;scene.render.bake.cage_extrusion=.004;scene.render.bake.max_ray_distance=.010;scene.render.bake.margin=10 + for bone in rig.pose.bones:bone.matrix_basis=Matrix.Identity(4) + low.modifiers['Transferred skeleton'].show_render=False;low.modifiers['Transferred skeleton'].show_viewport=False + for kind,filename in [('DIFFUSE','infernal_basecolor.png'),('NORMAL','infernal_normal.png'),('EMIT','infernal_orm.png')]: + image=bpy.data.images.new(filename,width=4096,height=4096,alpha=False) + if kind!='DIFFUSE':image.colorspace_settings.name='Non-Color' + node=final.node_tree.nodes.new('ShaderNodeTexImage');node.image=image;final.node_tree.nodes.active=node + if kind=='DIFFUSE':scene.render.bake.use_pass_direct=False;scene.render.bake.use_pass_indirect=False;scene.render.bake.use_pass_color=True + if kind=='EMIT': + for material in materials: + nodes=material.node_tree.nodes;links=material.node_tree.links + shader=next(n for n in nodes if n.type=='BSDF_PRINCIPLED') + combine=nodes.new('ShaderNodeCombineColor');combine.inputs[0].default_value=1 + for key,index in [('Roughness',1),('Metallic',2)]: + socket=shader.inputs[key] + if socket.is_linked:links.new(socket.links[0].from_socket,combine.inputs[index]) + else:combine.inputs[index].default_value=socket.default_value + emission=nodes.new('ShaderNodeEmission');links.new(combine.outputs[0],emission.inputs['Color']);links.new(emission.outputs[0],next(n for n in nodes if n.type=='OUTPUT_MATERIAL').inputs['Surface']) + bpy.ops.object.select_all(action='DESELECT');high.select_set(True);low.select_set(True);bpy.context.view_layer.objects.active=low + bpy.ops.object.bake(type=kind) + if kind=='NORMAL': + pixels=np.array(image.pixels[:],dtype=np.float32).reshape(-1,4) + empty=np.max(pixels[:,:3],axis=1)<.001 + pixels[empty,:3]=(.5,.5,1) + image.pixels.foreach_set(pixels.ravel()) + image.filepath_raw=str(out/filename);image.file_format='PNG';image.save();image.pack();log('baked',filename) + shader=next(n for n in final.node_tree.nodes if n.type=='BSDF_PRINCIPLED') + if kind=='DIFFUSE':final.node_tree.links.new(node.outputs['Color'],shader.inputs['Base Color']) + if kind=='NORMAL': + normal=final.node_tree.nodes.new('ShaderNodeNormalMap');final.node_tree.links.new(node.outputs['Color'],normal.inputs['Color']);final.node_tree.links.new(normal.outputs['Normal'],shader.inputs['Normal']) + if kind=='EMIT': + separate=final.node_tree.nodes.new('ShaderNodeSeparateColor');final.node_tree.links.new(node.outputs['Color'],separate.inputs[0]);final.node_tree.links.new(separate.outputs['Green'],shader.inputs['Roughness']);final.node_tree.links.new(separate.outputs['Blue'],shader.inputs['Metallic']) + low.modifiers['Transferred skeleton'].show_render=True;low.modifiers['Transferred skeleton'].show_viewport=True + + + # Exposed arms use a dedicated skin material, so rays through close printed + # contacts can never copy black clothing or hair onto their albedo. + skin=final.copy();skin.name='Infernal exposed arm skin' + shader=next(n for n in skin.node_tree.nodes if n.type=='BSDF_PRINCIPLED') + for key,value in [('Base Color',(.36,.012,.022,1)),('Roughness',.58),('Metallic',0.0)]: + socket=shader.inputs[key] + for link in list(socket.links):skin.node_tree.links.remove(link) + socket.default_value=value + from infernal_seams import cloth_at_point + low.data.materials.append(skin);region=low.data.attributes['SemanticRegion'].data + for face in low.data.polygons: + p=face.center + zo=p.z+.15;a=abs(p.x) + boundary=float(np.interp(zo,[1.,1.12,1.30,1.40,1.50,1.70],[.21,.21,.205,.15,.135,.135])) + anatomical_arm=.96boundary and a<.30 and -.0751.65 and p.y>.025 and a>.19) and not cloth_at_point(p):face.material_index=1 diff --git a/tools/infernal_facepaint.py b/tools/infernal_facepaint.py new file mode 100644 index 0000000..fc20228 --- /dev/null +++ b/tools/infernal_facepaint.py @@ -0,0 +1,47 @@ +"""Continuous facial paint aligned to the supplied sculpt's actual landmarks.""" +import bpy,numpy as np + +def apply_facepaint(material): + size=1024 + xx=np.linspace(-.085,.085,size,dtype=np.float32) + zz=np.linspace(1.76,1.98,size,dtype=np.float32) + x,z=np.meshgrid(xx,zz);a=np.abs(x) + pixels=np.zeros((size,size,4),dtype=np.float32) + def paint(mask,color): + pixels[mask,:3]=color;pixels[mask,3]=1 + eye_z=1.889+.20*(a-.031) + ellipse=((a-.031)/.019)**2+((z-eye_z)/.0057)**2 + paint(ellipse<1.30,(.012,.003,.007)) + paint(ellipse<.90,(.32,.27,.16)) + iris=((a-.031)/.0057)**2+((z-eye_z)/.0064)**2 + paint((ellipse<.90)&(iris<1),(.18,.080,.005)) + paint((ellipse<.90)&(iris<.60),(.45,.24,.018)) + paint((ellipse<.90)&(abs(a-.031)<.0016),(.003,.002,.002)) + glint=((a-.029)/.0012)**2+((z-eye_z-.0022)/.0012)**2 + paint((ellipse<.90)&(glint<1),(.9,.85,.65)) + eyebrow_z=1.911+.22*(a-.030)-3.0*(a-.030)**2 + paint((abs(a-.031)<.024)&(abs(z-eyebrow_z)<.0025*(1-abs(a-.031)/.029)),(.010,.002,.005)) + lips=(x/.026)**2+((z-1.817)/.0080)**2 + paint(lips<1,(.075,.0025,.012)) + paint((lips<.75)&(z<1.817),(.15,.005,.025)) + line_z=1.819-.0018*np.cos(x/.026*np.pi) + paint((lips<1)&(abs(z-line_z)<.00065),(.020,.001,.003)) + paint((lips<.5)&(z<1.815)&(z>1.814),(.22,.015,.035)) + image=bpy.data.images.new('Infernal aligned facial paint',width=size,height=size,alpha=True) + image.colorspace_settings.name='Non-Color';image.pixels.foreach_set(pixels.ravel());image.pack() + nodes=material.node_tree.nodes;links=material.node_tree.links + geometry=nodes.new('ShaderNodeNewGeometry');split=nodes.new('ShaderNodeSeparateXYZ');links.new(geometry.outputs['Position'],split.inputs[0]) + def math_node(operation,socket,value): + node=nodes.new('ShaderNodeMath');node.operation=operation;links.new(socket,node.inputs[0]);node.inputs[1].default_value=value;return node.outputs[0] + u=math_node('MULTIPLY_ADD',split.outputs['X'],1/.17) + # MULTIPLY_ADD has a separate add input. + u.node.inputs[2].default_value=.5 + v=math_node('MULTIPLY_ADD',split.outputs['Z'],1/.22);v.node.inputs[2].default_value=-1.61/.22 + vector=nodes.new('ShaderNodeCombineXYZ');links.new(u,vector.inputs['X']);links.new(v,vector.inputs['Y']) + texture=nodes.new('ShaderNodeTexImage');texture.image=image;texture.extension='CLIP';links.new(vector.outputs[0],texture.inputs['Vector']) + front=math_node('LESS_THAN',split.outputs['Y'],.015) + alpha=nodes.new('ShaderNodeMath');alpha.operation='MULTIPLY';links.new(front,alpha.inputs[0]);links.new(texture.outputs['Alpha'],alpha.inputs[1]) + shader=next(n for n in nodes if n.type=='BSDF_PRINCIPLED') + mix=nodes.new('ShaderNodeMixRGB');mix.blend_type='MIX';mix.inputs[1].default_value=shader.inputs['Base Color'].default_value + if shader.inputs['Base Color'].is_linked:links.new(shader.inputs['Base Color'].links[0].from_socket,mix.inputs[1]) + links.new(alpha.outputs[0],mix.inputs[0]);links.new(texture.outputs['Color'],mix.inputs[2]);links.new(mix.outputs[0],shader.inputs['Base Color']) diff --git a/tools/infernal_seams.py b/tools/infernal_seams.py new file mode 100644 index 0000000..749214a --- /dev/null +++ b/tools/infernal_seams.py @@ -0,0 +1,126 @@ +"""Paint contours traced from orthographic renders of the actual supplied sculpt. +Body guides: 1400 px, ortho .96 m, focus original Z 1.45. +Boot guides: 1400 px, ortho .62 m, focus original Z .42. +""" +import bpy,numpy as np +from pathlib import Path +from mathutils import Vector +from mathutils.kdtree import KDTree +_FILL_CLOTH=None +_FILL_SKIN=None +_MASKS={} +_DEPTHS={} + +FRONT=[(525,416),(550,420),(570,432),(590,436),(602,458),(620,469),(630,486),(648,499),(663,520),(679,542),(690,550),(700,542),(710,554),(729,528),(746,503),(761,485),(775,465),(790,451),(806,435),(823,423),(839,418),(862,406),(884,443),(905,480),(919,528),(917,567),(907,610),(889,627),(866,690),(860,758),(875,820),(914,866),(1007,931),(1020,937),(1012,964),(994,980),(967,993),(948,1008),(920,1019),(897,1025),(883,1052),(867,1045),(853,1022),(826,1040),(805,1037),(792,1065),(777,1090),(753,1119),(731,1145),(713,1170),(700,1185),(688,1184),(673,1164),(648,1142),(628,1115),(609,1094),(591,1069),(578,1041),(568,1043),(557,1034),(547,1007),(532,1000),(509,1023),(498,1013),(486,988),(464,978),(444,1009),(429,1007),(415,977),(405,947),(387,939),(397,918),(430,902),(464,880),(492,863),(503,844),(510,798),(514,745),(512,707),(506,668),(499,630),(476,612),(461,583),(458,549),(464,505),(478,465),(496,434)] +COLLAR=[(622,201),(641,207),(663,215),(683,227),(700,237),(720,226),(741,214),(774,199),(775,231),(777,263),(784,284),(814,303),(782,314),(782,340),(767,320),(746,325),(737,344),(718,353),(713,376),(700,403),(685,376),(680,352),(658,344),(650,323),(631,321),(621,334),(620,320),(596,324),(612,301),(621,275),(621,234)] +BACK=[(548,380),(852,380),(863,550),(862,730),(883,808),(913,861),(950,901),(980,934),(1000,965),(982,994),(964,1005),(944,1007),(935,979),(916,995),(899,1013),(881,1012),(875,974),(854,991),(844,1025),(824,1028),(817,1007),(811,1052),(794,1102),(778,1143),(764,1168),(745,1158),(750,1120),(755,1080),(739,1052),(713,1037),(686,1037),(661,1050),(637,1079),(614,1112),(590,1141),(569,1156),(554,1135),(558,1095),(572,1055),(588,1025),(574,1006),(565,1029),(549,1026),(539,1006),(524,1026),(506,1019),(503,992),(485,986),(478,1009),(462,1015),(449,998),(434,985),(419,995),(408,979),(414,951),(432,919),(465,888),(488,866),(510,844),(520,798),(527,740),(531,648),(536,533)] +BOOT_FRONT=[(0,301),(392,298),(420,302),(450,301),(464,296),(465,278),(480,270),(510,264),(550,261),(590,261),(620,263),(640,269),(644,284),(659,290),(681,291),(699,282),(718,294),(745,303),(750,280),(770,271),(806,264),(847,262),(885,264),(921,270),(938,279),(938,298),(964,303),(1009,299),(1400,301),(1400,1400),(0,1400)] +BOOT_BACK=[(0,303),(395,299),(425,290),(465,280),(507,272),(548,264),(586,264),(620,267),(660,277),(700,285),(734,276),(780,268),(818,264),(850,264),(890,269),(938,281),(982,293),(1009,303),(1400,303),(1400,1400),(0,1400)] + +def mask_image(name,polygons): + if name in _MASKS:return bpy.data.images[name] + size=2048;pixels=np.zeros((size,size,4),dtype=np.float32) + for polygon in polygons: + vertices=np.array(polygon,dtype=np.float64)*size/1400 + for row in range(size): + yy=row+.5;cross=[] + for a,b in zip(vertices,np.roll(vertices,-1,axis=0)): + if (a[1]<=yylo:pixels[size-1-row,lo:hi,:3]=1 + pixels[:,:,3]=1 + image=bpy.data.images.new(name,width=size,height=size,alpha=True);image.colorspace_settings.name='Non-Color';image.pixels.foreach_set(pixels.ravel());image.pack();_MASKS[name]=pixels;return image + +def add_sculpt_seams(nodes,links,x,y,z): + def math(operation,socket,value): + n=nodes.new('ShaderNodeMath');n.operation=operation;links.new(socket,n.inputs[0]) + if isinstance(value,(int,float)):n.inputs[1].default_value=value + else:links.new(value,n.inputs[1]) + return n.outputs[0] + def sample(name,polygons,width,bottom,back=False): + xx=math('MULTIPLY',x,-1) if back else x + u=math('MULTIPLY_ADD',xx,1/width);u.node.inputs[2].default_value=.5 + v=math('MULTIPLY_ADD',z,1/width);v.node.inputs[2].default_value=-bottom/width + vector=nodes.new('ShaderNodeCombineXYZ');links.new(u,vector.inputs['X']);links.new(v,vector.inputs['Y']) + tex=nodes.new('ShaderNodeTexImage');tex.image=polygons if isinstance(polygons,bpy.types.Image) else mask_image(name,polygons);tex.extension='CLIP';links.new(vector.outputs[0],tex.inputs['Vector']);return tex.outputs['Color'] + side=math('MULTIPLY_ADD',y,12);side.node.inputs[2].default_value=.5 + side=math('MAXIMUM',math('MINIMUM',side,1),0) + def blend(front,back): + mix=nodes.new('ShaderNodeMixRGB');links.new(side,mix.inputs[0]);links.new(front,mix.inputs[1]);links.new(back,mix.inputs[2]);return mix.outputs[0] + def visible(mask,depth): + delta=math('SUBTRACT',math('ADD',y,.5),depth) + near=math('LESS_THAN',math('ABSOLUTE',delta,0),.018) + return math('MULTIPLY',mask,near) + front=sample('Sculpt garment front',[FRONT,COLLAR],.96,.97) + back=sample('Sculpt garment back',[BACK,COLLAR],.96,.97,True) + front_depth=sample('Front depth',_DEPTHS['front'][0],.96,.97) + back_depth=sample('Back depth',_DEPTHS['back'][0],.96,.97,True) + body=math('MAXIMUM',visible(front,front_depth),visible(back,back_depth)) + boots=blend(sample('Sculpt boot rim front',[BOOT_FRONT],.62,.11),sample('Sculpt boot rim back',[BOOT_BACK],.62,.11,True)) + return math('MAXIMUM',body,boots) + + +def prepare_depths(high): + # Project onto the visible sculpt surface, not every surface behind it. + # This keeps the black ruffle from being projected onto a nearby forearm. + output=Path(__file__).resolve().parent.parent/'Demon_v0.19/captures/infernal' + scene=bpy.data.scenes.new('Sculpt seam depth');scene.render.engine='BLENDER_EEVEE' + scene.render.resolution_x=2048;scene.render.resolution_y=2048;scene.render.resolution_percentage=100;scene.render.film_transparent=True + scene.render.image_settings.file_format='OPEN_EXR';scene.render.image_settings.color_depth='32';scene.render.image_settings.color_mode='RGBA' + obj=high.copy();obj.hide_render=False;scene.collection.objects.link(obj) + mat=bpy.data.materials.new('Surface depth');mat.use_nodes=True;n=mat.node_tree.nodes;l=mat.node_tree.links;n.clear() + geo=n.new('ShaderNodeNewGeometry');split=n.new('ShaderNodeSeparateXYZ');l.new(geo.outputs['Position'],split.inputs[0]) + add=n.new('ShaderNodeMath');add.operation='ADD';l.new(split.outputs['Y'],add.inputs[0]);add.inputs[1].default_value=.5 + emission=n.new('ShaderNodeEmission');l.new(add.outputs[0],emission.inputs[0]);out=n.new('ShaderNodeOutputMaterial');l.new(emission.outputs[0],out.inputs[0]);scene.view_layers[0].material_override=mat + data=bpy.data.cameras.new('Seam projection camera');camera=bpy.data.objects.new('Seam projection camera',data);scene.collection.objects.link(camera);scene.camera=camera;data.type='ORTHO';data.ortho_scale=.96 + for side,yy in [('front',-6),('back',6)]: + camera.location=(0,yy,1.30);camera.rotation_euler=(Vector((0,0,1.30))-camera.location).to_track_quat('-Z','Y').to_euler() + scene.render.filepath=str(output/('seam-depth-'+side+'.exr'));bpy.ops.render.render(scene=scene.name,write_still=True) + image=bpy.data.images.load(scene.render.filepath,check_existing=False);pixels=np.array(image.pixels[:],dtype=np.float32).reshape(2048,2048,4);_DEPTHS[side]=(image,pixels) + bpy.data.objects.remove(obj,do_unlink=True);bpy.data.objects.remove(camera,do_unlink=True);bpy.data.scenes.remove(scene) + mask_image('Sculpt garment front',[FRONT,COLLAR]);mask_image('Sculpt garment back',[BACK,COLLAR]) + prepare_hidden_fill(high) + +def cloth_at_point(point): + x,y,z=point;z+=.15;seen=False + for side in ['front','back']: + xx=-x if side=='back' else x + u=(xx/.96+.5)*2048;v=(z-.97)/.96*2048 + if not (0<=u<2048 and 0<=v<2048):continue + column=int(u);row=int(v) + mask=_MASKS['Sculpt garment '+side][row,column,0] + depth=_DEPTHS[side][1][row,column,0] + if abs(y+.5-depth)<.018: + seen=True + if mask>.5:return True + if not seen and _FILL_CLOTH is not None and 1.09.5 + view=(abs(points[:,1]+.5-depth)<.006)&(original_z>.97)&(original_z<1.93)&(abs(points[:,0])<.48) + visible|=view;clothing|=view&mask + body=(original_z>1.09)&(original_z<1.85)&(abs(points[:,0])<.26) + cloth_ids=np.flatnonzero(clothing&body);skin_ids=np.flatnonzero(visible&~clothing&body) + _FILL_CLOTH=KDTree(len(cloth_ids));_FILL_SKIN=KDTree(len(skin_ids)) + for i in cloth_ids:_FILL_CLOTH.insert(points[i],int(i)) + for i in skin_ids:_FILL_SKIN.insert(points[i],int(i)) + _FILL_CLOTH.balance();_FILL_SKIN.balance() + fill=np.zeros(n,dtype=np.float32) + for i in np.flatnonzero(~visible&body): + _,_,a=_FILL_CLOTH.find(points[i]);_,_,b=_FILL_SKIN.find(points[i]) + if a0] + if boundary:bmesh.ops.holes_fill(bm,edges=boundary,sides=0) + foot_side=bm.verts.layers.int.new('FootSide') + for vertex in bm.verts: + if vertex[region]==0 and vertex.co.z<.95: + sign=1 if sum(f.calc_center_median().x for f in vertex.link_faces)>0 else -1 + vertex[foot_side]=sign + if abs(vertex.co.x)<1e-6:vertex.co.x=sign*.0003 + + for face in bm.faces: + if not all(vertex[region] in [4,5] for vertex in face.verts):continue + p=face.calc_center_median();p.x=abs(p.x);p.z+=.15 + if p.z<1.13 or p.z>1.65:continue + distance=10 + for a,b in zip(path[:-1],path[1:]): + delta=b-a;t=max(0,min(1,(p-a).dot(delta)/delta.length_squared));distance=min(distance,(p-a-delta*t).length) + radius=.046 if p.z>1.30 else .042 + if distance>radius:remove.append(face) + if remove:bmesh.ops.delete(bm,geom=remove,context='FACES') + for side in [4,5]: + edges=[e for e in bm.edges if e.is_boundary and all(v[region]==side for v in e.verts)] + if edges:bmesh.ops.holes_fill(bm,edges=edges,sides=0) + bmesh.ops.recalc_face_normals(bm,faces=list(bm.faces));bmesh.ops.triangulate(bm,faces=list(bm.faces));bm.to_mesh(obj.data);bm.free();obj.data.validate(clean_customdata=False);obj.data.update() + obj['arm_contacts_cleaned']=True + print('INFERNAL trimmed print-contact arm fins',len(remove),flush=True) + +def refine_weights(obj): + clean_arm_contacts(obj) + attrs=obj.data.attributes['SemanticRegion'].data + names={g.name:g for g in obj.vertex_groups} + for vertex in obj.data.vertices: + x,y,z=vertex.co;zo=z+.15;region=attrs[vertex.index].value + if region==0 and z<.95: + side='L' if x>0 else 'R' + if z<.18: + for group in list(vertex.groups):obj.vertex_groups[group.group].remove([vertex.index]) + names['foot.'+side].add([vertex.index],1,'REPLACE') + else: + for group in list(vertex.groups): + name=obj.vertex_groups[group.group].name + if name.endswith('.R' if side=='L' else '.L'):obj.vertex_groups[group.group].remove([vertex.index]) + total=sum(group.weight for group in vertex.groups) + for group in list(vertex.groups):obj.vertex_groups[group.group].add([vertex.index],group.weight/max(total,1e-8),'REPLACE') + if region not in [4,5]:continue + side='L' if x>0 else 'R' + if zo>1.65 and y>.085: + weights={'Wing.'+side:1.0} + else: + wrist=float(np.clip((1.17-zo)/.08,0,1)) + upper=float(np.clip((zo-1.36)/.12,0,1)) + shoulder=float(np.clip((zo-1.62)/.09,0,1)) + weights={'wrist.'+side:wrist,'lowerarm01.'+side:(1-wrist)*(1-upper),'upperarm01.'+side:upper*(1-shoulder),'spine02':upper*shoulder} + total=sum(weights.values()) + for group in list(vertex.groups):obj.vertex_groups[group.group].remove([vertex.index]) + for name,value in weights.items(): + if value>1e-5:names[name].add([vertex.index],value/total,'REPLACE') diff --git a/tools/infernal_surface.py b/tools/infernal_surface.py new file mode 100644 index 0000000..23044b4 --- /dev/null +++ b/tools/infernal_surface.py @@ -0,0 +1,68 @@ +"""Continuous PBR surface masks in object space; no triangle-sized paint edges.""" +import bpy,numpy as np +from mathutils.kdtree import KDTree + +def prepare_surface(high,low): + from infernal_seams import prepare_depths + prepare_depths(high) + kd=KDTree(len(low.data.vertices));regions=low.data.attributes['SemanticRegion'].data + for vertex in low.data.vertices:kd.insert(vertex.co,vertex.index) + kd.balance() + values=np.zeros(len(high.data.vertices),dtype=np.float32) + arms=np.zeros(len(high.data.vertices),dtype=np.float32) + for vertex in high.data.vertices: + _,index,_=kd.find(vertex.co);role=regions[index].value + x,y,z=vertex.co + zo=z+.15;a=abs(x) + boundary=float(np.interp(zo,[1.,1.12,1.30,1.40,1.50,1.70],[.21,.21,.205,.15,.135,.135])) + arm=(role in [4,5] or (.96boundary and -.0751.65 and y>.025 and a>.19) + arms[vertex.index]=1 if arm else 0 + values[vertex.index]=1 if (role in [1,2,3] or (a>.19 and y>.025 and zo>1.65)) and not arm else 0 + attribute=high.data.attributes.new('AppendageMask','FLOAT','POINT');attribute.data.foreach_set('value',values) + arm_attr=high.data.attributes.new('ExposedArmMask','FLOAT','POINT');arm_attr.data.foreach_set('value',arms) + material=bpy.data.materials.new('Infernal continuous surface paint');material.use_nodes=True + high.data.materials.clear();high.data.materials.append(material) + for face in high.data.polygons:face.material_index=0 + nodes=material.node_tree.nodes;links=material.node_tree.links + def op(operation,*args): + node=nodes.new('ShaderNodeMath');node.operation=operation + for i,value in enumerate(args): + if isinstance(value,(float,int)):node.inputs[i].default_value=value + else:links.new(value,node.inputs[i]) + return node.outputs[0] + def AND(*args): + result=args[0] + for v in args[1:]:result=op('MULTIPLY',result,v) + return result + def OR(*args): + result=args[0] + for v in args[1:]:result=op('MAXIMUM',result,v) + return result + def within(value,lo,hi):return AND(op('GREATER_THAN',value,lo),op('LESS_THAN',value,hi)) + geometry=nodes.new('ShaderNodeNewGeometry');split=nodes.new('ShaderNodeSeparateXYZ');links.new(geometry.outputs['Position'],split.inputs[0]) + x=split.outputs['X'];y=split.outputs['Y'];z=op('ADD',split.outputs['Z'],.15);a=op('ABSOLUTE',x) + attr=nodes.new('ShaderNodeAttribute');attr.attribute_name='AppendageMask' + appendage=attr.outputs['Fac'] + arm_attr=nodes.new('ShaderNodeAttribute');arm_attr.attribute_name='ExposedArmMask';exposed=op('SUBTRACT',1,arm_attr.outputs['Fac']) + hairline=op('SUBTRACT',1.968,op('MULTIPLY',a,.7)) + hair=OR(AND(op('LESS_THAN',a,.19),op('GREATER_THAN',z,hairline)),AND(op('LESS_THAN',a,.17),op('GREATER_THAN',y,.078),op('GREATER_THAN',z,1.30)),AND(within(a,.072,.215),op('LESS_THAN',y,.045),op('GREATER_THAN',z,1.52)),op('GREATER_THAN',z,1.99)) + from infernal_seams import add_sculpt_seams + clothes=add_sculpt_seams(nodes,links,x,y,z) + interior=nodes.new('ShaderNodeAttribute');interior.attribute_name='GarmentHiddenFill' + clothes=OR(clothes,interior.outputs['Fac']) + hair=AND(OR(hair,AND(within(a,.05,.19),op("GREATER_THAN",y,-.025),op("GREATER_THAN",z,1.68))),exposed) + shader=next(n for n in nodes if n.type=='BSDF_PRINCIPLED') + def mix_color(socket,mask,color): + mix=nodes.new('ShaderNodeMixRGB');links.new(mask,mix.inputs[0]) + if hasattr(socket,'node'):links.new(socket,mix.inputs[1]) + else:mix.inputs[1].default_value=(*socket,1) + mix.inputs[2].default_value=(*color,1) + return mix.outputs[0] + color=mix_color((.36,.012,.022),clothes,(.012,.015,.019)) + color=mix_color(color,hair,(.008,.009,.012));color=mix_color(color,appendage,(.014,.016,.019));links.new(color,shader.inputs['Base Color']) + # Matte skin and restrained leather highlights preserve the sculpted detail. + rough=op('SUBTRACT',.58,op('MULTIPLY',clothes,.14));rough=op('SUBTRACT',rough,op('MULTIPLY',hair,.08)) + links.new(rough,shader.inputs['Roughness']);shader.inputs['Metallic'].default_value=.03 + from infernal_facepaint import apply_facepaint + apply_facepaint(material) + return [material] diff --git a/tools/infernal_whip.py b/tools/infernal_whip.py new file mode 100644 index 0000000..385b4af --- /dev/null +++ b/tools/infernal_whip.py @@ -0,0 +1,27 @@ +"""Preserve the old animated whip and bind it to the retargeted right wrist.""" +import bpy + +def transfer_whip(scene,source,target): + whip=next((o for o in scene.objects if o.type=='MESH' and 'Flexible braided whip' in o.name),None) + if whip is None:return None + transform=target.data.bones['wrist.R'].matrix_local@source.data.bones['wrist.R'].matrix_local.inverted() + if whip.data.shape_keys: + for key in whip.data.shape_keys.key_blocks: + for point in key.data:point.co=transform@point.co + else: + for vertex in whip.data.vertices:vertex.co=transform@vertex.co + # Increase the actual cord radius, retaining its centreline and morph clips. + whip.data.update() + offsets=[vertex.normal.normalized()*.008 for vertex in whip.data.vertices] + if whip.data.shape_keys: + for key in whip.data.shape_keys.key_blocks: + for point,offset in zip(key.data,offsets):point.co+=offset + else: + for vertex,offset in zip(whip.data.vertices,offsets):vertex.co+=offset + whip.parent=target;whip.name='Infernal animated whip';whip.hide_render=False + for modifier in whip.modifiers: + if modifier.type=='ARMATURE':modifier.object=target + if whip.data.shape_keys and whip.data.shape_keys.animation_data: + whip.data.shape_keys.animation_data.action=None + for track in whip.data.shape_keys.animation_data.nla_tracks:track.mute=False + return whip diff --git a/tools/inspect_infernal.py b/tools/inspect_infernal.py new file mode 100644 index 0000000..469107c --- /dev/null +++ b/tools/inspect_infernal.py @@ -0,0 +1,35 @@ +import bpy +import json +from pathlib import Path +from mathutils import Vector + +root=Path(__file__).resolve().parent.parent +out=root/'Demon_v0.19/captures/infernal-inspect';out.mkdir(parents=True,exist_ok=True) +bpy.ops.wm.read_factory_settings(use_empty=True) +bpy.ops.wm.stl_import(filepath=str(root/'tools/model_sources/infernal.stl')) +model=bpy.context.object;model.name='Infernal source - untouched statue' +original=list(model.dimensions) +model.scale*=2.2/model.dimensions.z +bpy.context.view_layer.update() +points=[model.matrix_world@Vector(c) for c in model.bound_box] +lo=Vector(tuple(min(p[i] for p in points) for i in range(3)));hi=Vector(tuple(max(p[i] for p in points) for i in range(3))) +model.location-=Vector(((lo.x+hi.x)/2,(lo.y+hi.y)/2,lo.z)) +bpy.ops.object.transform_apply(location=True,rotation=True,scale=True) +scene=bpy.context.scene;scene.render.engine='BLENDER_WORKBENCH' +scene.render.resolution_x=1100;scene.render.resolution_y=1100;scene.render.resolution_percentage=100 +scene.display.shading.light='STUDIO';scene.display.shading.color_type='SINGLE';scene.display.shading.single_color=(.58,.58,.61) +scene.display.shading.show_cavity=True;scene.display.shading.cavity_type='BOTH';scene.display.shading.curvature_ridge_factor=1.2;scene.display.shading.curvature_valley_factor=1.0 +scene.display.shading.background_type='WORLD';scene.world=bpy.data.worlds.new('Inspection background');scene.world.color=(.10,.11,.13) +scene.view_settings.view_transform='Standard' +camera_data=bpy.data.cameras.new('Inspection Camera');camera=bpy.data.objects.new('Inspection Camera',camera_data);scene.collection.objects.link(camera);scene.camera=camera +camera_data.type='ORTHO';camera_data.ortho_scale=max(2.55,model.dimensions.x*1.15) +focus=Vector((0,0,1.1)) +for name,at in [('front',(0,-6,1.15)),('back',(0,6,1.15)),('side',(6,0,1.15)),('angle',(4,-6,2.9))]: + camera.location=at;camera.rotation_euler=(focus-camera.location).to_track_quat('-Z','Y').to_euler() + scene.render.filepath=str(out/(name+'.png'));bpy.ops.render.render(write_still=True) +coords=[v.co.z for v in model.data.vertices] +import numpy as np +report={'source_dimensions':original,'normalized_dimensions':list(model.dimensions),'vertices':len(model.data.vertices),'triangles':len(model.data.polygons),'z_percentiles':np.percentile(coords,[0,1,3,5,10,15,20,25,50,75,95,100]).tolist()} +(out/'source_report.json').write_text(json.dumps(report,indent=2)) +bpy.ops.wm.save_as_mainfile(filepath=str(out/'source_inspection.blend')) +print('INFERNAL_INSPECT',json.dumps(report),flush=True) diff --git a/tools/model_sources/SOURCES.json b/tools/model_sources/SOURCES.json new file mode 100644 index 0000000..4fe0032 --- /dev/null +++ b/tools/model_sources/SOURCES.json @@ -0,0 +1,11 @@ +{ + "provided_by_user": true, + "source_archive": "infernal.zip", + "archive_entry": "infernal .stl", + "source_stl_sha256": "9a0bad3fe47628b07b2bac1af2a22dbebc153f7bf4274346822515aab2801d3e", + "color_reference": "color_reference.png", + "color_reference_sha256": "34d8c86eb62cc36bb8dac449be8601893cb80c6b5f19e33dae563d5658d6a877", + "animation_source": "Demon_v0.19/art/succubus/succubus_v02.glb", + "paint_boundary_reference": "approved_paint_boundary.png", + "paint_boundary_sha256": "3193824095b8eafb02e0771085e00bc3b9d303f5d53e777972d11b63d71d6e8c" +} \ No newline at end of file diff --git a/tools/model_sources/approved_paint_boundary.png b/tools/model_sources/approved_paint_boundary.png new file mode 100644 index 0000000..bbbb20d Binary files /dev/null and b/tools/model_sources/approved_paint_boundary.png differ diff --git a/tools/model_sources/color_reference.png b/tools/model_sources/color_reference.png new file mode 100644 index 0000000..bbe645e Binary files /dev/null and b/tools/model_sources/color_reference.png differ diff --git a/tools/model_sources/infernal.stl b/tools/model_sources/infernal.stl new file mode 100644 index 0000000..aacf55d --- /dev/null +++ b/tools/model_sources/infernal.stl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a0bad3fe47628b07b2bac1af2a22dbebc153f7bf4274346822515aab2801d3e +size 78487084 diff --git a/tools/model_sources/infernal_game.blend b/tools/model_sources/infernal_game.blend new file mode 100644 index 0000000..3b4a2fc --- /dev/null +++ b/tools/model_sources/infernal_game.blend @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65f694afeb0742a50014da627323f7042b9182271a760116464ee0c166d928f3 +size 18761281 diff --git a/tools/validate_infernal.py b/tools/validate_infernal.py new file mode 100644 index 0000000..e330f8f --- /dev/null +++ b/tools/validate_infernal.py @@ -0,0 +1,31 @@ +"""Validate the actual optimized mesh, paint protection and all transferred clips.""" +import bpy,numpy as np,json,struct +from pathlib import Path +r=Path(__file__).resolve().parent.parent;out=r/'Demon_v0.19/reviews/infernal_v01' +bpy.ops.wm.open_mainfile(filepath=str(r/'tools/model_sources/infernal_game.blend')) +o=bpy.data.objects['Infernal_Game_Mesh'];rig=bpy.data.objects['INFERNAL_RIG'];v=np.array([tuple(x.co) for x in o.data.vertices]);edges=np.array([tuple(e.vertices) for e in o.data.edges]);initial=np.linalg.norm(v[edges[:,0]]-v[edges[:,1]],axis=1) +assert len(rig.data.bones)==166 +assert np.isfinite(v).all() and v[:,2].min()>-.0001 +floor=v[v[:,2]<.01];assert len(floor)>0 and abs(floor[:,0]).max()<.13,'pedestal left below feet' +assert len(o.data.polygons)<100000 +for vertex in o.data.vertices:assert abs(sum(group.weight for group in vertex.groups)-1)<.001 +skin=next(m for m in o.data.materials if m.name=='Infernal exposed arm skin');shader=next(n for n in skin.node_tree.nodes if n.type=='BSDF_PRINCIPLED') +assert not shader.inputs['Base Color'].is_linked and shader.inputs['Base Color'].default_value[0]>.3 +for name in ['infernal_basecolor.png','infernal_normal.png','infernal_orm.png']: + image=bpy.data.images[name];assert tuple(image.size)==(4096,4096) +for t in rig.animation_data.nla_tracks:t.mute=True +metrics={} +for clip in ['Idle','Walk','Whip']: + action=bpy.data.actions['Infernal / '+clip];rig.animation_data.action=action;maximum=0.;max_edge=0. + for frame in range(1,int(action.frame_range[1])+1,4): + bpy.context.scene.frame_set(frame);bpy.context.view_layer.update();ev=o.evaluated_get(bpy.context.evaluated_depsgraph_get());mesh=ev.to_mesh();p=np.array([tuple(x.co) for x in mesh.vertices]);ev.to_mesh_clear() + assert np.isfinite(p).all() + maximum=max(maximum,float(np.linalg.norm(p-v,axis=1).max()));growth=np.linalg.norm(p[edges[:,0]]-p[edges[:,1]],axis=1)-initial;max_edge=max(max_edge,float(growth.max())) + if growth.max()>.14: + edge=edges[growth.argmax()];print('BAD EDGE',clip,frame,[(v[i].round(3).tolist(),[(o.vertex_groups[x.group].name,round(x.weight,3)) for x in o.data.vertices[i].groups]) for i in edge],float(growth.max()),flush=True) + assert maximum<1.2,(clip,maximum) + assert max_edge<.15,(clip,'long stretched film',max_edge) + metrics[clip]={'frames':int(action.frame_range[1]),'max_vertex_travel_m':round(maximum,5),'max_edge_growth_m':round(max_edge,5)} +b=(out/'infernal_game.glb').read_bytes();length=struct.unpack_from('