Skip to content

Native Windows video motion capture with ExMR, FlowHMR and GVHMR, contact correction, humanoid retargeting, and FBX/VMD export.

Python

Render original-resolution character textures with bounded caching

toyxyz312925c287e3
diff --git a/SOURCE_MANIFEST.json b/SOURCE_MANIFEST.json
index 9db9008..eb6f8f3 100644
--- a/SOURCE_MANIFEST.json
+++ b/SOURCE_MANIFEST.json
@@ -86,8 +86,8 @@
},
{
"path": "docs/AGENT_GUIDE.md",
- "bytes": 11372,
- "sha256": "319e485c2d15b495af8983bb12b9d608654a8e7a145d336a2ee52347d9ca5f41"
+ "bytes": 11497,
+ "sha256": "e83a93812b8ab368595202d33313d92c2ba1b5a43ace1361fba6734d222f1437"
},
{
"path": "docs/BUILD.md",
@@ -96,13 +96,13 @@
},
{
"path": "docs/USER_GUIDE.md",
- "bytes": 27164,
- "sha256": "dd9c07ae0cfddd10f1ab157376220bdf5218ba2b124ecfeb2ceb2ff4a058ca9d"
+ "bytes": 27504,
+ "sha256": "adca6d25a2c46ad71b7319cfb6e7b25ac12820df4d9d9ec8c5ee1b8f11138e73"
},
{
"path": "docs/VALIDATION.md",
- "bytes": 4911,
- "sha256": "8f5d4a81659420bf939ee394b9005bcfa988e00f42a1b346e3c7090d16f5bade"
+ "bytes": 6413,
+ "sha256": "1d7d6ba9c064699c3d864dd9f8cabbf55d0ee5e4ab4256513eb1e98ec41d9c70"
},
{
"path": "docs/images/rgbmocap-workspace.png",
@@ -946,8 +946,8 @@
},
{
"path": "mocap/character_data.py",
- "bytes": 4629,
- "sha256": "bc4ce431193e5dabfe03f0853a41923cb19eeb70cb49c04f130ce2b6ad546e0b"
+ "bytes": 6278,
+ "sha256": "77a20ec5e67cb0c3ba11faa969c69b79e2f50f02851ccc4be64b24c2758e497d"
},
{
"path": "mocap/character_export_dialog.py",
@@ -956,13 +956,18 @@
},
{
"path": "mocap/character_gl.py",
- "bytes": 3033,
- "sha256": "4c26ad91fd2d90b00470342856052afba7054c9002ce1109a43e6fa1cb1f7e26"
+ "bytes": 7166,
+ "sha256": "3402f72a07ca3ef91821b33d5408d86c70db3330cd9fcd9351403aeaeba2447b"
+ },
+ {
+ "path": "mocap/character_textures.py",
+ "bytes": 4763,
+ "sha256": "c6fc076605cb60e60d081e059a694869ea8bb63ca555b741a1b7586343974e03"
},
{
"path": "mocap/character_ui.py",
- "bytes": 20079,
- "sha256": "031e926548715c3784ed790dbbb3d7931ef528cbd4830ad04d6143129211f9fd"
+ "bytes": 20360,
+ "sha256": "afbf6182f4dbf6377268aa1dc22515b06e658387eebf4ebd803f43be26b8ccd5"
},
{
"path": "mocap/compute_policy.py",
@@ -1316,8 +1321,13 @@
},
{
"path": "mocap/retarget/blender_io.py",
- "bytes": 12567,
- "sha256": "85523cfe0101b991d622fe9c8a10d92dae2dc214a2601f8329c0ee82d9d924af"
+ "bytes": 13050,
+ "sha256": "fd5a61ade1be86471e90f6f8c6aa743d74614b5d33fcaf7ead9fe5058936055c"
+ },
+ {
+ "path": "mocap/retarget/blender_textures.py",
+ "bytes": 4136,
+ "sha256": "92227e679f25e44da457803baf75a0aa112c55ee6b5e551ba9d85ff16ee6d247"
},
{
"path": "mocap/retarget/bounded_stabilizer.py",
diff --git a/docs/AGENT_GUIDE.md b/docs/AGENT_GUIDE.md
index 41cd651..bcf5f27 100644
--- a/docs/AGENT_GUIDE.md
+++ b/docs/AGENT_GUIDE.md
@@ -41,7 +41,7 @@ See [the full workflow and controls](USER_GUIDE.md#start-here). Do not confuse v
- **File > Import Character...** accepts Mixamo-style FBX, VRM and PMX, and adds the character in rest pose below people. Up to eight characters per project are supported.
- Right-click the character and choose **Retarget > [source person]**. Review via timeline; row checkboxes control visibility. Custom bone mapping is not implemented. Unsupported or incomplete mappings must not be silently relabeled.
- The source's applied contact timings are used. **Apply Correction** refreshes linked characters; after other source changes retarget again. Targets that cannot be reached do not cause bone stretching. Different limb lengths can change travel distance, and editing may be required in a 3D tool.
-- **Export Character...** offers FBX with or without character mesh, and VMD for PMX characters. VMD is sampled at 30 fps for the same PMX model; facial motion and hair/clothing physics are not generated. Character FBX preserves its imported rest hierarchy and keys body bones, not the armature object. The character viewport uses simplified vertex colors, not full-resolution texture rendering.
+- **Export Character...** offers FBX with or without character mesh, and VMD for PMX characters. VMD is sampled at 30 fps for the same PMX model; facial motion and hair/clothing physics are not generated. Character FBX preserves its imported rest hierarchy and keys body bones, not the armature object. The character viewport uses original-resolution base-color textures with simplified lighting. Texture caches are prepared off the GUI thread, independently of motion; existing characters prepare them on first display.
- A separate Blender runtime is used for character import, rig evaluation and baking/export; the user need not open Blender for the app workflow. Preserve upstream licenses and the bundled Blender environment. See [character retargeting](USER_GUIDE.md#character-retargeting) and [FBX/Blender](USER_GUIDE.md#fbx-and-blender).
## Projects, state and protection
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index e367853..9af6224 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -56,8 +56,12 @@ the first animation frame does not replace the rest pose. Existing retargeted
characters can be exported again to use the corrected FBX rest-pose handling.
Known humanoid mappings are automatic; custom bone mapping is not yet available.
-Files missing required body bones are rejected with a message. Viewport materials
-use a simplified color preview.
+Files missing required body bones are rejected with a message. The viewport shows
+base-color textures at their original resolution, with simplified lighting rather
+than a full material/physics renderer. Existing characters prepare a texture cache
+in the background on first display; reimporting or retargeting is not required.
+Textures are reused during playback. Oversized textures produce a clear error
+instead of being silently reduced in resolution.
### Included Blender runtime
diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md
index 1be9a08..429dc7a 100644
--- a/docs/VALIDATION.md
+++ b/docs/VALIDATION.md
@@ -71,6 +71,27 @@ interactive playback, standalone MMD playback or testing on other GPUs.
public checkout. These checks did not repeat standalone MMD playback or test
other GPUs, network shares or every possible Windows path.
+## Original-resolution character textures (2026-10-27)
+
+- Mixamo FBX, VRM and PMX samples retained their original image dimensions and UVs.
+ A pre-existing PMX asset prepared its texture cache without reimport or retargeting.
+ Sampled GPU-deformed vertex buffers were unchanged, including a 474-frame take.
+- Isolated 1920 x 1080 GPU checks ran 600 draws per sample, excluding the first 50
+ from timing statistics. Original-texture median / p95 draw times were
+ 0.108 / 0.264 ms (FBX), 0.331 / 0.536 ms (VRM), 0.466 / 0.697 ms (PMX rest),
+ and 0.411 / 0.617 ms (PMX animation). The largest recorded draw was 2.50 ms.
+ These are isolated renderer measurements, not complete application frame times.
+- Twelve renderer load/close cycles kept the handle count constant. Process RAM
+ rose about 13 MiB during warm-up and stabilized in the last three cycles.
+ Three loader playback/seek cycles had no missing animation windows, constant
+ handles and less than 0.1 MiB additional RAM. Timer lateness reached 15.7 ms;
+ these checks do not establish video/audio synchronization or universal FPS.
+ Cancelling background texture preparation shut the loader down in 0.107 seconds.
+- Original images are cached once per character on CPU and uploaded once per
+ loaded renderer, with mipmaps for distant viewing. Motion buffers remain bounded.
+ Full PBR materials and general translucent-material sorting are not implemented.
+ Tests and generated character assets remained outside the public checkout.
+
These checks describe the recorded examples, not a guarantee for every video,
character or computer. Model weights and registered body data remain separate and
subject to their providers' terms. Review the applicable third-party notices and
diff --git a/mocap/character_data.py b/mocap/character_data.py
index c22fc79..054e120 100644
--- a/mocap/character_data.py
+++ b/mocap/character_data.py
@@ -11,12 +11,14 @@ class CharacterLoader(QThread):
changed=Signal()
failed=Signal(str,str)
evicted=Signal(str)
+ preparing=Signal(str)
def __init__(self,parent=None):
- super().__init__(parent);self.condition=Condition();self.pending=OrderedDict();self.data={};self.windows={};self.stop=False;self.epoch=0;self.errors=set()
- def request(self,path,frame=0):
+ super().__init__(parent);self.condition=Condition();self.pending=OrderedDict();self.data={};self.windows={};self.stop=False;self.epoch=0;self.errors=set();self.texture_sources={}
+ def request(self,path,frame=0,texture_source=None):
key=str(path)
with self.condition:
if key in self.errors:return
+ if texture_source is not None:self.texture_sources[key]=str(texture_source)
self.pending[key]=(frame,self.epoch);self.condition.notify()
def frame(self,path,index):
key=str(path)
@@ -32,12 +34,12 @@ class CharacterLoader(QThread):
self.request(path,index);return None
def reset(self):
with self.condition:
- self.epoch+=1;self.pending.clear();self.windows.clear();self.errors.clear();self.condition.notify()
+ self.epoch+=1;self.pending.clear();self.windows.clear();self.errors.clear();self.texture_sources.clear();self.condition.notify()
def close(self):
with self.condition:self.stop=True;self.condition.notify()
self.wait()
with self.condition:
- self.pending.clear();self.windows.clear();self.data.clear()
+ self.pending.clear();self.windows.clear();self.data.clear();self.texture_sources.clear()
def run(self):
arrays=OrderedDict();epoch=-1
try:
@@ -63,6 +65,23 @@ class CharacterLoader(QThread):
asset['key']=key
from .name_overlay import character_samples
asset['name_samples']=character_samples(asset)
+ from .character_textures import load,validate_geometry
+ source=str(Path(self.texture_sources.get(key,key)).resolve())
+ textures=next((v['textures'] for v in self.data.values() if v.get('textures',{}).get('key')==source),None)
+ if textures is None:
+ self.preparing.emit('Loading original character textures...')
+ textures=load(source,asset,lambda:self.stop or requested!=self.epoch)
+ else:validate_geometry(textures['metadata'],asset)
+ asset['textures']=textures
+ # Shared images count once across rest/animated takes. Keep
+ # texture residency bounded independently of clip length.
+ def resident_bytes():
+ unique={v['textures']['key']:v['textures']['bytes'] for v in self.data.values()}
+ unique[source]=textures['bytes']
+ return sum(unique.values())
+ if resident_bytes()>2048*1024**2:
+ raise ValueError('Character textures exceed the 2 GB loaded-preview limit. Open fewer characters in this project.')
+ if self.stop or requested!=self.epoch:continue
a=FrameArray(p/'preview-frames.npy');arrays[key]=a
if a.shape[-2:]!=(4,4) or a.shape[1]>4096:raise ValueError('Invalid character animation palette')
self.data[key]=asset
@@ -76,6 +95,7 @@ class CharacterLoader(QThread):
self.ready.emit(key,dict(asset=self.data[key],frames=a.shape[0],palette=a.shape[1]))
self.changed.emit()
except Exception as exc:
+ if self.stop or requested!=self.epoch:continue
with self.condition:self.errors.add(key)
self.failed.emit(key,str(exc))
finally:
diff --git a/mocap/character_gl.py b/mocap/character_gl.py
index bb3daf6..3f9e615 100644
--- a/mocap/character_gl.py
+++ b/mocap/character_gl.py
@@ -1,6 +1,7 @@
"""GPU skinning for imported characters; only a compact bone palette changes per frame."""
import numpy as np
-from PySide6.QtOpenGL import QOpenGLShader,QOpenGLBuffer
+from PySide6.QtOpenGL import QOpenGLShader,QOpenGLBuffer,QOpenGLTexture
+from PySide6.QtGui import QImage,QMatrix4x4,QVector4D
from .mesh_gl import MeshRenderer
SKIN='''#version 430 core
@@ -30,6 +31,20 @@ void main(){gl_Position=mvp*sceneTransform*vec4(position,1);n=mat3(sceneTransfor
FRAGMENT='''#version 430 core
in vec3 n;in vec3 c;out vec4 color;
void main(){vec3 normal=normalize(n);float light=.60+.35*max(0,dot(normal,normalize(vec3(-.4,.8,-.6))));color=vec4(c*light,1);}'''
+TEXTURE_VERTEX='''#version 430 core
+struct Vertex {vec4 position;vec4 normal;};
+layout(std430,binding=1) readonly buffer Output {Vertex vertices[];};
+layout(location=0) in vec3 corner;
+uniform mat4 mvp;uniform mat4 sceneTransform;out vec3 n;out vec2 uv;
+void main(){Vertex v=vertices[int(corner.x)];gl_Position=mvp*sceneTransform*v.position;
+n=mat3(sceneTransform)*v.normal.xyz;uv=corner.yz;}'''
+TEXTURE_FRAGMENT='''#version 430 core
+in vec3 n;in vec2 uv;out vec4 color;
+uniform sampler2D baseTexture;uniform bool hasTexture;uniform vec4 baseColor;
+void main(){vec4 c=hasTexture?texture(baseTexture,uv):baseColor;
+if(c.a<.1)discard;
+float light=.60+.35*max(0,dot(normalize(n),normalize(vec3(-.4,.8,-.6))));
+color=vec4(c.rgb*light,1);}'''
class CharacterRenderer(MeshRenderer):
def __init__(self):
@@ -37,6 +52,8 @@ class CharacterRenderer(MeshRenderer):
self.skin.removeAllShaders();self.surface.removeAllShaders()
self.skin=self.program(((QOpenGLShader.Compute,SKIN),))
self.surface=self.program(((QOpenGLShader.Vertex,VERTEX),(QOpenGLShader.Fragment,FRAGMENT)))
+ self.textured=self.program(((QOpenGLShader.Vertex,TEXTURE_VERTEX),(QOpenGLShader.Fragment,TEXTURE_FRAGMENT)))
+ self.textures={};self.batches=[]
def load(self,asset,palette):
if self.asset_key==asset['key']:return
@@ -52,5 +69,60 @@ class CharacterRenderer(MeshRenderer):
self.surface.enableAttributeArray(i);self.surface.setAttributeBuffer(i,0x1406,offset,3,32)
self.colors=self.buffer(np.asarray(asset['colors'],np.float32))
self.surface.enableAttributeArray(2);self.surface.setAttributeBuffer(2,0x1406,0,3,12)
- self.vao.release();self.surface.release();self.asset_key=asset['key'];self.frame_key=None
+ self.vao.release();self.surface.release()
+ try:
+ if asset.get('textures'):
+ data=asset['textures']
+ self.vao.bind();self.textured.bind()
+ self.corners=self.buffer(data['corners'])
+ self.textured.enableAttributeArray(0);self.textured.setAttributeBuffer(0,0x1406,0,3,12)
+ self.vao.release();self.textured.release()
+ for name,pixels in data['images'].items():
+ h,w=pixels.shape[:2]
+ limit=int(self.gl.glGetIntegerv(0x0D33))
+ if max(w,h)>limit:raise ValueError(f'Original texture {w}x{h} exceeds this GPU limit ({limit}).')
+ image=QImage(pixels.data,w,h,w*4,QImage.Format_RGBA8888)
+ texture=QOpenGLTexture(image,QOpenGLTexture.GenerateMipMaps)
+ self.textures[name]=texture
+ if not texture.isCreated():raise RuntimeError('Cannot allocate original character texture')
+ texture.setMinificationFilter(QOpenGLTexture.LinearMipMapLinear)
+ texture.setMagnificationFilter(QOpenGLTexture.Linear)
+ texture.setWrapMode(QOpenGLTexture.Repeat)
+ self.gpu_bytes+=sum(max(1,w>>i)*max(1,h>>i)*4 for i in range(max(w,h).bit_length()))
+ self.batches=data['batches']
+ self.check('character textures')
+ except Exception:
+ self.release_buffers();raise
+ self.asset_key=asset['key'];self.frame_key=None
self.check('character load')
+
+ def draw(self,eye,basis,width,height,color=(.71,.71,.71),transform=None,clear_depth=True):
+ if not self.batches:
+ return super().draw(eye,basis,width,height,color,transform,clear_depth)
+ projection=QMatrix4x4();projection.perspective(40,width/max(1,height),.03,2000)
+ view=np.eye(4);view[:3,:3]=basis*np.array([[1],[1],[-1]]);view[:3,3]=-view[:3,:3]@eye
+ shader=self.textured;gl=self.gl;shader.bind()
+ shader.setUniformValue('mvp',projection*QMatrix4x4(*view.ravel().tolist()))
+ shader.setUniformValue('sceneTransform',QMatrix4x4(*np.asarray(transform if transform is not None else np.eye(4)).ravel().tolist()))
+ gl.glUniform1i(shader.uniformLocation('baseTexture'),0)
+ gl.glBindBufferBase(0x90D2,1,self.vertices.bufferId())
+ gl.glEnable(0x0B71);gl.glDepthMask(True);gl.glDepthFunc(0x0201)
+ for flag in (0x0B90,0x0C11,0x0B44,0x0BE2):gl.glDisable(flag)
+ if clear_depth:gl.glClear(0x100)
+ self.vao.bind()
+ for batch in self.batches:
+ texture=self.textures.get(batch['image'])
+ gl.glUniform1i(shader.uniformLocation('hasTexture'),int(texture is not None))
+ shader.setUniformValue('baseColor',QVector4D(*batch['color']))
+ if texture:texture.bind(0)
+ gl.glDrawArrays(0x4,batch['start'],batch['count'])
+ gl.glBindTexture(0x0DE1,0)
+ self.vao.release();shader.release();gl.glDisable(0x0B71)
+
+ def release_buffers(self):
+ for texture in self.textures.values():texture.destroy()
+ self.textures.clear();self.batches=[]
+ super().release_buffers()
+
+ def close(self):
+ super().close();self.textured.removeAllShaders()
diff --git a/mocap/character_textures.py b/mocap/character_textures.py
new file mode 100644
index 0000000..37df8e5
--- /dev/null
+++ b/mocap/character_textures.py
@@ -0,0 +1,90 @@
+"""Load full-size texture caches on the character I/O thread, never during painting."""
+import hashlib
+import json
+import os
+from pathlib import Path
+import subprocess
+import time
+
+import numpy as np
+
+from .retarget.file_paths import io_path
+
+CACHE = 'preview-textures-v1'
+
+
+def load(source, asset, cancelled):
+ source = Path(source).resolve()
+ folder = Path(io_path(source / CACHE))
+ if not (folder / 'manifest.json').is_file():
+ from .retarget.runtime import blender
+ entry = Path(__file__).parent / 'retarget' / 'blender_entry.py'
+ command = [str(blender()), '-b', '--factory-startup', '--disable-autoexec', '--threads', '3',
+ '--python-exit-code', '1', '--python', str(entry), '--', 'textures', str(source)]
+ env = dict(os.environ, PYTHONUTF8='1', PYTHONIOENCODING='utf-8')
+ with open(io_path(source / 'texture-preview.log'), 'w', encoding='utf8') as log:
+ process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, env=env,
+ creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
+ try:
+ deadline = time.monotonic() + 180
+ while process.poll() is None:
+ if cancelled():
+ raise InterruptedError('Texture preparation cancelled')
+ if time.monotonic() > deadline:
+ raise RuntimeError('Texture preparation timed out. See texture-preview.log in the character asset folder.')
+ time.sleep(.1)
+ if process.returncode:
+ raise RuntimeError('Cannot prepare original character textures. See texture-preview.log in the character asset folder.')
+ finally:
+ if process.poll() is None:
+ process.terminate()
+ try:
+ process.wait(timeout=3)
+ except subprocess.TimeoutExpired:
+ process.kill(); process.wait()
+ manifest = folder / 'manifest.json'
+ if manifest.stat().st_size > 4 * 1024**2:
+ raise ValueError('Character texture metadata exceeds limits')
+ meta = json.loads(manifest.read_text(encoding='utf8'))
+ validate_geometry(meta, asset)
+ if (folder / 'corners.npy').stat().st_size > asset['faces'].size*12 + 4096:
+ raise ValueError('Character UV cache exceeds geometry limits')
+ corners = np.load(folder / 'corners.npy', allow_pickle=False)
+ if corners.shape != (asset['faces'].size, 3) or corners.dtype != np.float32 or not np.isfinite(corners).all():
+ raise ValueError('Invalid character texture UV cache')
+ ids = corners[:, 0]
+ if np.any(ids < 0) or np.any(ids >= len(asset['vertices'])) or np.any(ids != np.floor(ids)):
+ raise ValueError('Invalid character texture vertex indices')
+ images, total = {}, corners.nbytes
+ for key, size in meta['images'].items():
+ if not key.startswith('image') or not key[5:].isdigit() or len(size) != 2:
+ raise ValueError('Invalid character texture image entry')
+ w, h = size
+ if not isinstance(w, int) or not isinstance(h, int) or min(w, h) < 1 or w*h*4 > 256*1024**2:
+ raise ValueError('Character texture size exceeds limits')
+ total += w*h*4
+ if total > 576*1024**2:
+ raise ValueError('Character textures exceed memory limits')
+ filename = folder / (key + '.npy')
+ if filename.stat().st_size > w*h*4 + 4096:
+ raise ValueError('Invalid character texture file size')
+ pixels = np.load(filename, allow_pickle=False)
+ if pixels.shape != (h, w, 4) or pixels.dtype != np.uint8:
+ raise ValueError('Invalid character texture pixel data')
+ images[key] = pixels
+ end = 0
+ for batch in meta['batches']:
+ if (batch['start'] != end or not isinstance(batch['count'], int) or batch['count'] <= 0
+ or batch['count'] % 3 or batch['image'] is not None and batch['image'] not in images
+ or len(batch['color']) != 4 or not np.isfinite(batch['color']).all()):
+ raise ValueError('Invalid character texture material batch')
+ end += batch['count']
+ if end != len(corners):
+ raise ValueError('Incomplete character texture triangles')
+ return dict(key=str(source), corners=corners, images=images, batches=meta['batches'], metadata=meta, bytes=total)
+
+
+def validate_geometry(meta, asset):
+ if (meta.get('version') != 1 or meta['vertices'] != len(asset['vertices'])
+ or meta['faces_sha256'] != hashlib.sha256(asset['faces'].tobytes()).hexdigest()):
+ raise ValueError('Character texture and animation geometry do not match. Reimport the character.')
diff --git a/mocap/character_ui.py b/mocap/character_ui.py
index e2ddcd6..c065029 100644
--- a/mocap/character_ui.py
+++ b/mocap/character_ui.py
@@ -18,6 +18,7 @@ class CharacterWorkspace:
self.character_loader.evicted.connect(lambda key:self.character_assets.pop(key,None))
self.character_loader.changed.connect(self.motion_view.update)
self.character_loader.failed.connect(lambda key,msg:self.status.setText('Character preview: '+msg))
+ self.character_loader.preparing.connect(lambda msg:self.status.setText(msg) if self.character_process is None else None)
self.character_loader.start()
self.character_timer=QTimer(self);self.character_timer.setInterval(500)
self.character_timer.timeout.connect(self.character_progress)
@@ -311,6 +312,7 @@ class CharacterWorkspace:
def character_ready(self,key,data):
if self.character_loader.stop:return
self.character_assets[key]=data
+ if self.status.text()=='Loading original character textures...':self.status.setText('Character preview ready.')
if self.motion_view.joints is None and not self.motion_view._camera_initialized:
v=data['asset']['vertices'];lo=v.min(0);hi=v.max(0)
self.motion_view.scene_center=(lo+hi)*.5
@@ -333,6 +335,6 @@ class CharacterWorkspace:
path=self.character_path(c['animation']+'/'+take['folder']);frame=int((time_-take['start'])*take['fps']+1e-6);transform=take.get('transform')
data=self.character_assets.get(str(path))
if not data:
- self.character_loader.request(path,frame);continue
+ self.character_loader.request(path,frame,self.character_path(c['asset']));continue
matrix=self.character_loader.frame(path,frame)
if matrix is not None:yield c,data,matrix,frame,transform
diff --git a/mocap/retarget/blender_io.py b/mocap/retarget/blender_io.py
index 1bdc68f..4a97505 100644
--- a/mocap/retarget/blender_io.py
+++ b/mocap/retarget/blender_io.py
@@ -86,6 +86,9 @@ def import_character(filename, out):
metadata=dict(kind=kind,name=filename.stem,vertices=count,bones=len(arm.data.bones))
if kind=='pmx':metadata['mmd_import_scale']=.08
Path(io_path(out/'import.json')).write_text(json.dumps(metadata),encoding='utf8')
+ from .blender_textures import extract
+ report('Preparing original-resolution textures')
+ extract(out)
def vertex_colors(obj):
@@ -175,6 +178,12 @@ def preview(out,arm,keyed,n):
def main(args):
mode,folder,*rest=args;out=Path(folder)
if mode=='import':import_character(Path(rest[0]),out)
+ elif mode=='textures':
+ kind=json.loads(Path(io_path(out/'import.json')).read_text(encoding='utf8'))['kind']
+ if kind not in {'mixamo','vrm','pmx'}:raise ValueError('Unsupported character kind')
+ bpy.ops.wm.open_mainfile(filepath=io_path(out/f'{kind}-rest.blend'),load_ui=False)
+ from .blender_textures import extract
+ extract(out)
elif mode=='bake':
from . import blender_bake
blender_bake.OUT=out
diff --git a/mocap/retarget/blender_textures.py b/mocap/retarget/blender_textures.py
new file mode 100644
index 0000000..d504363
--- /dev/null
+++ b/mocap/retarget/blender_textures.py
@@ -0,0 +1,86 @@
+"""Original-size base-color images and per-corner UVs, independent of motion."""
+import hashlib
+import json
+import shutil
+import uuid
+from pathlib import Path
+
+import bpy
+import numpy as np
+
+from .file_paths import io_path
+
+CACHE = 'preview-textures-v1'
+
+
+def extract(out):
+ out = Path(io_path(out))
+ if (out / CACHE / 'manifest.json').is_file():
+ return
+ temp = out / ('.textures-' + uuid.uuid4().hex)
+ temp.mkdir()
+ try:
+ images, sizes, batches, corners, faces = {}, {}, [], [], []
+ offset = total = 0
+ for obj in bpy.context.scene.objects:
+ if obj.type != 'MESH':
+ continue
+ mesh = obj.data
+ mesh.calc_loop_triangles()
+ uv = mesh.uv_layers.active
+ faces.extend([[offset + i for i in t.vertices] for t in mesh.loop_triangles])
+ for mi in sorted({t.material_index for t in mesh.loop_triangles}):
+ mat = mesh.materials[mi] if mi < len(mesh.materials) else None
+ color = list(mat.diffuse_color) if mat else [.65, .65, .65, 1.]
+ tex = None
+ if mat and mat.use_nodes:
+ nodes = mat.node_tree.nodes
+ bs = next((n for n in nodes if n.type == 'BSDF_PRINCIPLED'), None)
+ inp = bs.inputs.get('Base Color') if bs else None
+ if inp is not None:
+ color = list(inp.default_value)
+ if inp.is_linked:
+ node = inp.links[0].from_node
+ if node.type == 'TEX_IMAGE':
+ tex = node.image
+ if tex is None:
+ node = next((n for n in nodes if n.type == 'TEX_IMAGE' and n.image and 'shade' not in n.name.lower()), None)
+ if node:
+ tex = node.image
+ key = None
+ if tex and uv and tex.size[0] and tex.size[1]:
+ key = images.get(tex.name)
+ if key is None:
+ w, h = tex.size
+ total += w * h * 4
+ if w * h * 4 > 256 * 1024**2 or total > 512 * 1024**2:
+ raise ValueError('Original character textures exceed the 256 MB/image or 512 MB/character preview limit.')
+ key = 'image' + str(len(images))
+ images[tex.name] = key
+ sizes[key] = [w, h]
+ pixels = np.empty(w * h * 4, np.float32)
+ tex.pixels.foreach_get(pixels)
+ np.clip(pixels, 0, 1, out=pixels)
+ pixels *= 255
+ np.save(temp / (key + '.npy'), pixels.reshape(h, w, 4).astype(np.uint8))
+ del pixels
+ start = len(corners)
+ for tri in mesh.loop_triangles:
+ if tri.material_index == mi:
+ for li in tri.loops:
+ corners.append([offset + mesh.loops[li].vertex_index, *(uv.data[li].uv if uv else (0, 0))])
+ batches.append(dict(start=start, count=len(corners)-start, image=key, color=color))
+ offset += len(mesh.vertices)
+ faces = np.asarray(faces, np.uint32)
+ with np.load(out / 'preview.npz', allow_pickle=False) as asset:
+ if len(asset['vertices']) != offset or not np.array_equal(asset['faces'], faces):
+ raise ValueError('Stored character geometry differs from the texture source. Reimport the character.')
+ np.save(temp / 'corners.npy', np.asarray(corners, np.float32))
+ metadata = dict(version=1, vertices=offset, faces_sha256=hashlib.sha256(faces.tobytes()).hexdigest(),
+ batches=batches, images=sizes)
+ (temp / 'manifest.json').write_text(json.dumps(metadata), encoding='utf8')
+ temp.rename(out / CACHE)
+ finally:
+ # Only this invocation's temporary directory, never a user asset.
+ if temp.exists():
+ shutil.rmtree(temp)