diff --git a/design/astral-projection/three/assets/makehuman-african-female-young.target.gz b/design/astral-projection/three/assets/makehuman-african-female-young.target.gz deleted file mode 100644 index 0a912e2e8..000000000 Binary files a/design/astral-projection/three/assets/makehuman-african-female-young.target.gz and /dev/null differ diff --git a/design/astral-projection/three/assets/makehuman-asian-male-young.target.gz b/design/astral-projection/three/assets/makehuman-asian-male-young.target.gz new file mode 100644 index 000000000..1372aabd0 Binary files /dev/null and b/design/astral-projection/three/assets/makehuman-asian-male-young.target.gz differ diff --git a/design/astral-projection/three/assets/makehuman-caucasian-male-young.target.gz b/design/astral-projection/three/assets/makehuman-caucasian-male-young.target.gz new file mode 100644 index 000000000..7c005444e Binary files /dev/null and b/design/astral-projection/three/assets/makehuman-caucasian-male-young.target.gz differ diff --git a/design/astral-projection/three/assets/makehuman-height-male-young-maxheight.target.gz b/design/astral-projection/three/assets/makehuman-height-male-young-maxheight.target.gz new file mode 100644 index 000000000..d5729aa69 Binary files /dev/null and b/design/astral-projection/three/assets/makehuman-height-male-young-maxheight.target.gz differ diff --git a/design/astral-projection/three/assets/makehuman-proportions-male-young-averagemuscle-averageweight-idealproportions.target.gz b/design/astral-projection/three/assets/makehuman-proportions-male-young-averagemuscle-averageweight-idealproportions.target.gz new file mode 100644 index 000000000..bedc62a10 Binary files /dev/null and b/design/astral-projection/three/assets/makehuman-proportions-male-young-averagemuscle-averageweight-idealproportions.target.gz differ diff --git a/design/astral-projection/three/assets/makehuman-proportions-male-young-averagemuscle-minweight-idealproportions.target.gz b/design/astral-projection/three/assets/makehuman-proportions-male-young-averagemuscle-minweight-idealproportions.target.gz new file mode 100644 index 000000000..fe98058a5 Binary files /dev/null and b/design/astral-projection/three/assets/makehuman-proportions-male-young-averagemuscle-minweight-idealproportions.target.gz differ diff --git a/design/astral-projection/three/assets/makehuman-proportions-male-young-maxmuscle-averageweight-idealproportions.target.gz b/design/astral-projection/three/assets/makehuman-proportions-male-young-maxmuscle-averageweight-idealproportions.target.gz new file mode 100644 index 000000000..02fce1381 Binary files /dev/null and b/design/astral-projection/three/assets/makehuman-proportions-male-young-maxmuscle-averageweight-idealproportions.target.gz differ diff --git a/design/astral-projection/three/assets/makehuman-proportions-male-young-maxmuscle-minweight-idealproportions.target.gz b/design/astral-projection/three/assets/makehuman-proportions-male-young-maxmuscle-minweight-idealproportions.target.gz new file mode 100644 index 000000000..02fce1381 Binary files /dev/null and b/design/astral-projection/three/assets/makehuman-proportions-male-young-maxmuscle-minweight-idealproportions.target.gz differ diff --git a/design/astral-projection/three/assets/makehuman-source.json b/design/astral-projection/three/assets/makehuman-source.json index 80f970ad5..aecbf2d74 100644 --- a/design/astral-projection/three/assets/makehuman-source.json +++ b/design/astral-projection/three/assets/makehuman-source.json @@ -7,19 +7,28 @@ "weights": "makehuman/data/rigs/default_weights.mhw", "weights_sha256": "0f3641d651ae3d00ad6b4ccee43142edb109d3bd909d27d9e4139ef1beed8625", "weights_licence": "CC0-1.0 (declared in the file header)", - "shape": "slender young adult female: makehuman/data/targets/macrodetails/{african,asian,caucasian}-female-young.target, one third each; macro weight 0.25, muscle 0.35, height 0.65 and ideal proportions mixed as MakeHuman mixes them from macrodetails/universal-female-young-*, macrodetails/height/female-young-*-maxheight (the four are one file) and macrodetails/proportions/female-young-*-idealproportions; then smaller hands and feet and a slightly longer neck in Breeze scripts/prepare-practice-human.py", + "shape": "two characters, each MakeHuman's own young-adult macro shape, mixed as MakeHuman mixes its macro targets: makehuman/data/targets/macrodetails/{asian,caucasian}-GENDER-young.target (0.9 and 0.1), macrodetails/universal-GENDER-young-*muscle-*weight and macrodetails/proportions/GENDER-young-*-idealproportions (ideal proportions) at each character's weight and muscle, and macrodetails/height/GENDER-young-*-maxheight (the four are one file). The petite woman: weight 0.10, muscle 0.45, height 0.60; then smaller hands and feet, narrower shoulders, a slightly longer neck, larger eyes, a smaller mouth, a shorter chin and a smaller jaw. The young man: weight 0.40, muscle 0.65, height 0.60, eyes a little larger. Both in Breeze scripts/prepare-practice-human.py.", "shape_files": { - "makehuman-african-female-young.target.gz": "cb57ae84a34b9ed0cf2c4e65909337827ab3da40663c0aa6524f5fe345c4f182", "makehuman-asian-female-young.target.gz": "47067a1afcaea462d751f1b8ad30e465b54dd22b3f28c8d8e7fc7344ddd7e02a", + "makehuman-asian-male-young.target.gz": "decf95b11819927fad59931e080046f84c36f6742f4fd6e74ab4a5665a1df4fd", "makehuman-caucasian-female-young.target.gz": "09559da0d7e7936b94f4898063620650e1e7489fa8459f859e67a70646482c62", + "makehuman-caucasian-male-young.target.gz": "b494e2c28d7c97cc997a4d64ac91b854e0037eb475cce042aaa5e5ec54ef8274", "makehuman-height-female-young-maxheight.target.gz": "db4021e632faa65c4a9b735fafe8bd2c84476047234557490985f6550e528071", + "makehuman-height-male-young-maxheight.target.gz": "db4021e632faa65c4a9b735fafe8bd2c84476047234557490985f6550e528071", "makehuman-proportions-female-young-averagemuscle-averageweight-idealproportions.target.gz": "862192427280d8695e7a212ce5b73ced42d8d469ff822781c07066149467d952", "makehuman-proportions-female-young-averagemuscle-minweight-idealproportions.target.gz": "0d80f8a42a0ecefe9bea6fe63808973dcb71db0b0717d50e9ad6247d1e60cac3", "makehuman-proportions-female-young-minmuscle-averageweight-idealproportions.target.gz": "6cfa5b6c82ad68a0255f8e567162b15edc225d41cfbac3a632cf5308c02cb3dd", "makehuman-proportions-female-young-minmuscle-minweight-idealproportions.target.gz": "304bb6ffb59e167d9a38d230336bea0996b12b27c3c76778f72257437f2eda08", + "makehuman-proportions-male-young-averagemuscle-averageweight-idealproportions.target.gz": "162b35ad3d297c532688e48976fe94d0826987c8353364791e8b20753e785217", + "makehuman-proportions-male-young-averagemuscle-minweight-idealproportions.target.gz": "36f2812c196c0677f86c39e5b8bc09bbbab2c85e94a8f73593410f7f5b4c039f", + "makehuman-proportions-male-young-maxmuscle-averageweight-idealproportions.target.gz": "2e1969967db03c78cfbb435a9c18c263290c3ebb37c7aadb4d0ff96f735c69be", + "makehuman-proportions-male-young-maxmuscle-minweight-idealproportions.target.gz": "2e1969967db03c78cfbb435a9c18c263290c3ebb37c7aadb4d0ff96f735c69be", "makehuman-universal-female-young-averagemuscle-minweight.target.gz": "1c16fee7ff8a5f3e7fd746fc3a400fb6139ec8bba8ecb8d28397f469bdccc629", "makehuman-universal-female-young-minmuscle-averageweight.target.gz": "1da31baecbf8b98430d8e6dca8000afe56d1063d112057d559c97f57a1b7eb7a", - "makehuman-universal-female-young-minmuscle-minweight.target.gz": "1a29b433bae8304b9254242226526799561eb2d25c691441cea599ebe6a04def" + "makehuman-universal-female-young-minmuscle-minweight.target.gz": "1a29b433bae8304b9254242226526799561eb2d25c691441cea599ebe6a04def", + "makehuman-universal-male-young-averagemuscle-minweight.target.gz": "591f4105390abc3b4d7691d33fcdd9737875922374f8d227652b8f94d600acea", + "makehuman-universal-male-young-maxmuscle-averageweight.target.gz": "06cbc0fb72830b88609f3cf05dc1c90006c13758b157002bec0a1921545c3da3", + "makehuman-universal-male-young-maxmuscle-minweight.target.gz": "5ba2c95a24e8cbc52ace6516e5368e1abf58bcfe51a8864101d489e1fb3476f1" }, "shape_licence": "CC0-1.0 (declared in each target file header)" } diff --git a/design/astral-projection/three/assets/makehuman-universal-male-young-averagemuscle-minweight.target.gz b/design/astral-projection/three/assets/makehuman-universal-male-young-averagemuscle-minweight.target.gz new file mode 100644 index 000000000..37c21a76e Binary files /dev/null and b/design/astral-projection/three/assets/makehuman-universal-male-young-averagemuscle-minweight.target.gz differ diff --git a/design/astral-projection/three/assets/makehuman-universal-male-young-maxmuscle-averageweight.target.gz b/design/astral-projection/three/assets/makehuman-universal-male-young-maxmuscle-averageweight.target.gz new file mode 100644 index 000000000..1b2ebd9c8 Binary files /dev/null and b/design/astral-projection/three/assets/makehuman-universal-male-young-maxmuscle-averageweight.target.gz differ diff --git a/design/astral-projection/three/assets/makehuman-universal-male-young-maxmuscle-minweight.target.gz b/design/astral-projection/three/assets/makehuman-universal-male-young-maxmuscle-minweight.target.gz new file mode 100644 index 000000000..c469cbcb5 Binary files /dev/null and b/design/astral-projection/three/assets/makehuman-universal-male-young-maxmuscle-minweight.target.gz differ diff --git a/design/figure-preview/README.md b/design/figure-preview/README.md index 97fc43489..1707f3533 100644 --- a/design/figure-preview/README.md +++ b/design/figure-preview/README.md @@ -1,19 +1,19 @@ # Figure preview -A native window for judging and tuning the shared practice figure. It plays -each practice's own choreography on the character from the practices -package (`figure/`): Tai Chi forms, two rounds of Sun Salutation, the -Workout's twelve exercises and the six astral techniques. It runs on Ziran -and Kryon's SDL/Cairo desktop host, without raylib. +A native window for judging and tuning the shared practice figures. It +plays each practice's own choreography on either character from the +practices package (`figure/`), the petite young woman or the young man: +Tai Chi forms, two rounds of Sun Salutation, the Workout's twelve exercises +and the six astral techniques. It runs on Ziran and Kryon's SDL/Cairo +desktop host, without raylib. Each practice plays on its own backdrop in Inner Breeze's illustration style: a lake terrace for Tai Chi, a sunrise hill for Sun Salutation, a woodland deck for the Workout and a moonlit veranda for astral projection. -The panel picks the practice and item, plays, pauses, scrubs and slows the -clock. It switches the finish off to show the bare surface on paper, and -can show Breeze's current flat figure for the same moment. It also tunes the -seam softening, the dried edges, the line, the texture and the colour -strength. Drag over her to turn around her; scroll to zoom. +The panel picks the woman or the man, the practice and item, plays, +pauses, scrubs and slows the clock, sets the colour strength and can show +Breeze's current flat figure for the same moment. Drag over the figure to +turn around it; scroll to zoom. This is its own small project so it can pin the Kryon that has `scene_skin` and portable shaders, and the practices commit that has the figure, @@ -41,12 +41,14 @@ checkout instead, for trying figure changes before they are pushed (add that checkout's figure code too). `./build/app/figure_preview --capture DIR` writes review frames to `DIR` and -exits without a window. Each frame is written three ways: the painted figure -on the practice's backdrop (`NAME.png`), her bare surface on paper -(`NAME-bare.png`) and Breeze's current flat figure for the same moment and -camera (`NAME-current.png`). The frames cover -Tai Chi's deepest stance, Sun Salutation's fold, lunge, plank, cobra and -downward dog, the Workout's lowest squat and lunge, and the astral exits. +exits without a window: the woman on the practice's backdrop (`NAME.png`) +and on a plain studio grey (`NAME-studio.png`), the man the same way +(`NAME-male.png`, `NAME-male-studio.png`), and Breeze's current flat figure +for the same moment and camera (`NAME-current.png`). The frames cover a +front and a turned portrait, Tai Chi's deepest stance, also at the angles +of the owner's two reference sculptures (`reference-female`, +`reference-male`), Sun Salutation's fold, lunge, plank, cobra and downward +dog, the Workout's lowest squat and lunge, and the astral exits. ## Profiling @@ -54,11 +56,12 @@ The window prints a timing report to its standard output (the launcher's journal) every 120 painted frames and when it closes: median and 95th percentile milliseconds over the last 240 frames for the whole frame and for each step (the practice's pose solve, the -figure's pose, skinning, cloth, render and readback, finish and ground -shadow, the backdrop, compositing, the astral double, the texture upload +figure's pose, skinning, the skirt and the normals, render and readback, +fading a translucent double, the contact shadow, the backdrop, compositing, the astral double, the texture upload and the panel's controls). `./build/app/figure_preview --profile PRACTICE` (`tai-chi`, `sun-salutation`, `workout` or `astral`) paints 240 frames -without a window and prints the same report; add `still` to hold one pose. +without a window and prints the same report; add `still` to hold one pose +and `male` to profile the man. ## Known limits diff --git a/design/figure-preview/figure_preview.zi b/design/figure-preview/figure_preview.zi index 990bcc2f0..10f18c2ab 100644 --- a/design/figure-preview/figure_preview.zi +++ b/design/figure-preview/figure_preview.zi @@ -1,8 +1,8 @@ -// A live preview of the shared practice figure: pick a practice and one of -// its items, play, pause, scrub or slow it down, turn and zoom around her, -// and switch the watercolor finish off to judge the bare surface. The poses -// are the practices' own (preview_practices.zi); the character is the -// practices package's figure. +// A live preview of the shared practice figures: pick the woman or the man, +// a practice and one of its items, play, pause, scrub or slow it down, turn +// and zoom around the figure, and set the colour strength. The poses are +// the practices' own (preview_practices.zi); the characters are the +// practices package's figures. // // figure_preview opens the window // figure_preview --capture DIR writes the review frames to DIR and exits @@ -53,7 +53,8 @@ PreviewState :: struct { seconds: float64 playing: bool speed: float64 - watercolor: bool + // FIGURE_FEMALE or FIGURE_MALE. + character: s32 // Shows Breeze's current flat figure instead, for comparison. current: bool turn: float64 @@ -62,25 +63,20 @@ PreviewState :: struct { dragging: bool drag_x: float32 drag_y: float32 - bleed: float32 - edge: float32 - contour: float32 - granulation: float32 colour: float32 } -preview_state: PreviewState = .{playing = true, speed = 1.0, watercolor = true, zoom = 1.0, - bleed = 0.15, edge = 0.25, contour = 0.6, granulation = 0.25, colour = 0.6}; -preview_media: FigureMedia; +preview_state: PreviewState = .{playing = true, speed = 1.0, zoom = 1.0, colour = 0.6}; +preview_woman: FigureMedia; +preview_man: FigureMedia; +// The character the painters were prepared for. +preview_prepared: s32; preview_backdrops: PreviewBackdrops; preview_library: PreviewLibrary; preview_body: FigurePainter; preview_twin: FigurePainter; preview_picture: Raster.Image; -// Two textures, used in turn: Kryon redraws an image when its texture -// changes, not when the same texture's pixels are updated. -preview_textures: [2]Texture2D; -preview_shown: s32; +preview_texture: Texture2D; preview_owner: Session; preview_painted_key: u64; preview_failed: bool; @@ -103,8 +99,10 @@ main :: (argc: s32, argv: **u8) -> s32 { return 1 } media: [1100]u8 - preview_media = FigureMediaLoad(PreviewJoin(media[:], practices, "/shared/watercolor")) - if !FigureMediaReady(*preview_media) || !PreviewBackdropsLoad(*preview_backdrops, practices) || + folder := PreviewJoin(media[:], practices, "/shared/figure") + preview_woman = FigureMediaLoad(folder, FIGURE_FEMALE) + preview_man = FigureMediaLoad(folder, FIGURE_MALE) + if !FigureMediaReady(*preview_woman) || !FigureMediaReady(*preview_man) || !PreviewBackdropsLoad(*preview_backdrops, practices) || !PreviewLibraryLoad(*preview_library, practices) { print("figure preview: could not read the figure media or the practices in %\n", practices) return 1 @@ -118,13 +116,21 @@ main :: (argc: s32, argv: **u8) -> s32 { practice = index } } - // A third argument "still" holds one pose, to tell the renderer's own - // cost from rebuilding the moving surface. - still := argc >= 4 && TextFromCString(argv[3]) == "still" - return PreviewProfileRun(*preview_media, *preview_backdrops, *preview_library, practice, 240, 600, 760, still) + // Further arguments: "still" holds one pose, to tell the renderer's + // own cost from rebuilding the moving surface; "male" profiles him. + still := false + character: s32 = FIGURE_FEMALE + for index: 3..argc - 1 { + still = still || TextFromCString(argv[index]) == "still" + if TextFromCString(argv[index]) == "male" { + character = FIGURE_MALE + } + } + return PreviewProfileRun(PreviewMedia(character), *preview_backdrops, *preview_library, practice, 240, 600, + 760, still) } if argc >= 3 && TextFromCString(argv[1]) == "--capture" { - return PreviewCapture(*preview_media, *preview_backdrops, *preview_library, TextFromCString(argv[2])) + return PreviewCapture(*preview_woman, *preview_man, *preview_backdrops, *preview_library, TextFromCString(argv[2])) } status := Desktop.RunTitled(PreviewDraw, 1360, 900, "Figure preview") PreviewProfileReport("live window, closing") @@ -193,6 +199,15 @@ PreviewDraw :: (session: Session, viewport: Rectangle) -> s32 { Text.Draw(session, Text.Props.{.key = 10, .bounds = .{x, y, width, 30.0}, .text = "Figure preview", .size = 22}) y += 42.0 + people: [2]Segmented.SegmentOption + people[0].label = "Woman" + people[1].label = "Man" + person := Segmented.Draw(session, Segmented.Props.{.key = 27, .bounds = .{x, y, width, 40.0}, + .selected_index = state.character, .has_selection = true}, people[:]).selected_index + if person != state.character && person >= 0 && person < FIGURE_CHARACTERS { + state.character = person + } + y += 52.0 options: [4]Segmented.SegmentOption options[0].label = "Tai Chi" options[1].label = "Sun" @@ -246,24 +261,9 @@ PreviewDraw :: (session: Session, viewport: Rectangle) -> s32 { state.speed = cast(float64)speed.value } y += 62.0 - state.watercolor = Toggle.Draw(session, Toggle.Props.{.key = 17, .bounds = .{x, y, width, 40.0}, - .label = "Watercolor finish", .value = state.watercolor}).value - y += 46.0 state.current = Toggle.Draw(session, Toggle.Props.{.key = 23, .bounds = .{x, y, width, 40.0}, .label = "Current flat figure", .value = state.current}).value y += 50.0 - state.bleed = Slider.Draw(session, Slider.Props.{.key = 25, .bounds = .{x, y, width, 56.0}, - .label = "Wet bleed", .value = state.bleed, .max = 1.0}).value - y += 60.0 - state.edge = Slider.Draw(session, Slider.Props.{.key = 18, .bounds = .{x, y, width, 56.0}, - .label = "Dried edges", .value = state.edge, .max = 1.0}).value - y += 60.0 - state.contour = Slider.Draw(session, Slider.Props.{.key = 19, .bounds = .{x, y, width, 56.0}, - .label = "Ink line", .value = state.contour, .max = 1.0}).value - y += 60.0 - state.granulation = Slider.Draw(session, Slider.Props.{.key = 20, .bounds = .{x, y, width, 56.0}, - .label = "Granulation", .value = state.granulation, .max = 1.0}).value - y += 60.0 state.colour = Slider.Draw(session, Slider.Props.{.key = 26, .bounds = .{x, y, width, 56.0}, .label = "Colour strength", .value = state.colour, .max = 1.0}).value y += 66.0 @@ -293,14 +293,13 @@ PreviewDraw :: (session: Session, viewport: Rectangle) -> s32 { return 0 } +PreviewMedia :: (character: s32) -> *FigureMedia { + return ifx character == FIGURE_MALE then *preview_man else *preview_woman +} + PreviewStyle :: () -> FigureStyle { style := FigureStyleDefault() - style.watercolor = preview_state.watercolor - style.wash.bleed = cast(float64)preview_state.bleed - style.wash.edge = cast(float64)preview_state.edge - style.wash.contour = cast(float64)preview_state.contour - style.wash.granulation = cast(float64)preview_state.granulation - style.wash.saturation = cast(float64)preview_state.colour + style.colour = cast(float64)preview_state.colour return style } @@ -314,7 +313,7 @@ PreviewPaintFigure :: (session: Session, area: Rectangle) { return } key := PreviewKey(width, height) - if key != preview_painted_key || preview_textures[preview_shown].id == 0 { + if key != preview_painted_key || preview_texture.id == 0 { clock := PreviewNow() moment := PreviewSample(*preview_library, state.practice, state.item, state.seconds) PreviewRecord(PREVIEW_PHASE_SOLVE, PreviewLap(*clock)) @@ -323,13 +322,19 @@ PreviewPaintFigure :: (session: Session, area: Rectangle) { camera := PreviewFlatOf(*moment, view) preview_failed = !PreviewFlatRender(camera, view, width, height, *preview_picture) } else { - preview_failed = !PreviewCompose(*preview_body, *preview_twin, *preview_media, *preview_backdrops, - state.practice, *moment, view, PreviewStyle(), width, height, *preview_picture) + // The painters are prepared for one character's surface. + if preview_prepared != state.character { + FigurePainterRelease(*preview_body) + FigurePainterRelease(*preview_twin) + preview_prepared = state.character + } + preview_failed = !PreviewCompose(*preview_body, *preview_twin, PreviewMedia(state.character), + *preview_backdrops, state.practice, *moment, view, PreviewStyle(), false, width, height, + *preview_picture) } unused PreviewLap(*clock) if !preview_failed { - next := 1 - preview_shown - texture := preview_textures[next] + texture := preview_texture if texture.id != 0 && (texture.width != width || texture.height != height || preview_owner.slot != session.slot || preview_owner.epoch != session.epoch) { BitmapImageRelease(preview_owner, texture) @@ -341,21 +346,15 @@ PreviewPaintFigure :: (session: Session, area: Rectangle) { } else if !BitmapImageUpdate(session, texture, preview_picture.pixels[:]) { preview_failed = true } - preview_textures[next] = texture - if texture.id != 0 && !preview_failed { - preview_shown = next - } + preview_texture = texture preview_painted_key = key PreviewRecord(PREVIEW_PHASE_UPLOAD, PreviewLap(*clock)) preview_painted = true } } - shown := preview_textures[preview_shown] - if shown.id != 0 { - // A new key with each new picture: Kryon's retained frames compare - // an image by its node and texture, not by the pixels behind it. - Image.Draw(session, Image.Props.{.key = cast(u64)(3 + preview_shown * 1000), .bounds = area, - .texture = shown, .smooth = true, .alt_text = "The practice figure"}) + if preview_texture.id != 0 { + Image.Draw(session, Image.Props.{.key = 3, .bounds = area, .texture = preview_texture, .smooth = true, + .alt_text = "The practice figure"}) } } @@ -363,11 +362,9 @@ PreviewPaintFigure :: (session: Session, area: Rectangle) { PreviewKey :: (width: s32, height: s32) -> u64 { state := *preview_state digest: u64 = 1469598103934665603 - values: [15]float64 = .[cast(float64)state.practice, cast(float64)state.item, state.seconds, - state.turn, state.lift, state.zoom, ifx state.watercolor then 1.0 else 0.0, - ifx state.current then 1.0 else 0.0, cast(float64)state.bleed, cast(float64)state.edge, - cast(float64)state.contour, cast(float64)state.granulation, cast(float64)state.colour, - cast(float64)width, cast(float64)height] + values: [10]float64 = .[cast(float64)state.practice, cast(float64)state.item, state.seconds, + state.turn, state.lift, state.zoom, cast(float64)state.character, + ifx state.current then 1.0 else 0.0, cast(float64)state.colour, cast(float64)width * 10000.0 + cast(float64)height] for value: values { bits := cast(u64)(value * 1000003.0 + 0.5) digest = digest * 1099511628211 + bits diff --git a/design/figure-preview/preview_capture.zi b/design/figure-preview/preview_capture.zi index 176eb4f26..e516d4214 100644 --- a/design/figure-preview/preview_capture.zi +++ b/design/figure-preview/preview_capture.zi @@ -1,10 +1,11 @@ // Composing a moment's picture, and the fixed review frames the capture -// mode writes: each practice's hardest poses for the figure, painted on the -// practice's backdrop, bare on paper, and Breeze's current flat figure. +// mode writes: each practice's hardest poses for both figures, on the +// practice's backdrop and on a plain studio grey, and Breeze's current flat +// figure. #import "figure_math" #import "figure_joints" #import "figure_paint" -#import "figure_wash" +#import "figure_finish" #import "preview_practices" #import "preview_flat" #import "preview_profile" @@ -17,7 +18,7 @@ #import "std/vec" Raster :: #import "std/image"; -// Each practice's painted backdrop, and the last one scaled to a picture. +// Each practice's backdrop, and the last one scaled to a picture. PreviewBackdrops :: struct { images: [4]Raster.Image covered: Raster.Image @@ -30,7 +31,7 @@ PreviewBackdropsLoad :: (backdrops: *PreviewBackdrops, practices: string) -> boo for practice: cast(s32)0..3 { folder: [1100]u8 path: [1200]u8 - name := PreviewJoin(folder[:], practices, "/shared/watercolor/backdrops/") + name := PreviewJoin(folder[:], practices, "/shared/figure/backdrops/") name = PreviewJoin(path[:], name, PreviewBackdropName(practice)) file: [1300]u8 loaded := LoadImagePixels(PreviewJoin(file[:], name, ".webp")) @@ -55,10 +56,10 @@ PreviewBackdropsRelease :: (backdrops: *PreviewBackdrops) { } // The body, and an astral twin over it, into OUT: on the practice's -// painted backdrop with the watercolor finish, on plain paper without. +// backdrop, or on a plain studio grey (STUDIO) for judging the figure. PreviewCompose :: (body: *FigurePainter, twin: *FigurePainter, media: *FigureMedia, backdrops: *PreviewBackdrops, practice: s32, moment: *PreviewMoment, view: FigureView, - style: FigureStyle, width: s32, height: s32, out: *Raster.Image) -> bool { + style: FigureStyle, studio: bool, width: s32, height: s32, out: *Raster.Image) -> bool { still: FigureEffect if !FigurePaint(body, media, *moment.body, view, style, still, width, height) { return false @@ -75,8 +76,8 @@ PreviewCompose :: (body: *FigurePainter, twin: *FigurePainter, media: *FigureMed // strength, then the figure is laid over it. backdrop := *backdrops.images[practice] covered := *backdrops.covered - painted := style.watercolor && Raster.ImageValid(backdrop) - vivid := ifx painted then FigureVivid(style.wash) else -1.0 + painted := !studio && Raster.ImageValid(backdrop) + vivid := ifx painted then FigureVivid(style) else -1.0 if covered.width != width || covered.height != height || backdrops.covered_practice != practice || backdrops.covered_vivid != vivid { if painted { @@ -92,9 +93,9 @@ PreviewCompose :: (body: *FigurePainter, twin: *FigurePainter, media: *FigureMed } covered.width = width covered.height = height - paper: [4]u8 = .[243, 237, 225, 255] + grey: [4]u8 = .[218, 218, 221, 255] for index: 0..covered.pixels.count - 1 { - covered.pixels[index] = paper[index % 4] + covered.pixels[index] = grey[index % 4] } } backdrops.covered_practice = practice @@ -140,8 +141,8 @@ PreviewProfileRun :: (media: *FigureMedia, backdrops: *PreviewBackdrops, library moment := PreviewSample(library, practice, item, seconds) PreviewRecord(PREVIEW_PHASE_SOLVE, PreviewLap(*clock)) view := PreviewViewOf(*moment, 0.0, 0.0, 1.0) - if !PreviewCompose(*body, *twin, media, backdrops, practice, *moment, view, FigureStyleDefault(), width, - height, *picture) { + if !PreviewCompose(*body, *twin, media, backdrops, practice, *moment, view, FigureStyleDefault(), false, + width, height, *picture) { print("figure profile: frame % could not be painted\n", frame) return 1 } @@ -163,18 +164,40 @@ PreviewShot :: struct { item: s32 seconds: float64 name: string + // How far the camera turns about her, in radians. + turn: float64 + // A close view of the head and shoulders. + portrait: bool } -PreviewCapture :: (media: *FigureMedia, backdrops: *PreviewBackdrops, library: *PreviewLibrary, +// Writes NAME.png (her on the backdrop), NAME-studio.png (her on grey), the +// same with -male for him, and NAME-current.png (Breeze's flat figure). +PreviewCapture :: (woman: *FigureMedia, man: *FigureMedia, backdrops: *PreviewBackdrops, library: *PreviewLibrary, directory: string) -> s32 { shots: [24]PreviewShot count: s32 full := PreviewDefaultItem(library, PREVIEW_TAI_CHI) shots[count] = .{PREVIEW_TAI_CHI, full, 9.0, "tai-chi-9s"} count += 1 + shots[count] = .{PREVIEW_TAI_CHI, full, 9.0, "portrait"} + shots[count].portrait = true + count += 1 + shots[count] = .{PREVIEW_TAI_CHI, full, 9.0, "portrait-turned"} + shots[count].turn = -0.65 + shots[count].portrait = true + count += 1 shots[count] = .{PREVIEW_TAI_CHI, full, 131.0, "tai-chi-131s"} count += 1 - shots[count] = .{PREVIEW_TAI_CHI, full, PreviewLowest(library, PREVIEW_TAI_CHI, full), "tai-chi-deepest-stance"} + lowest := PreviewLowest(library, PREVIEW_TAI_CHI, full) + shots[count] = .{PREVIEW_TAI_CHI, full, lowest, "tai-chi-deepest-stance"} + count += 1 + // The owner's reference sculpts' angles (figure/design/reference): + // the woman from her front left, the man from behind on his left. + shots[count] = .{PREVIEW_TAI_CHI, full, lowest, "reference-female"} + shots[count].turn = -0.55 + count += 1 + shots[count] = .{PREVIEW_TAI_CHI, full, lowest, "reference-male"} + shots[count].turn = 2.45 count += 1 // The Sun Salutation's folds and floor poses, each once it is reached. names: [5]string = .["sun-forward-fold", "sun-lunge", "sun-plank", "sun-cobra", "sun-downward-dog"] @@ -208,49 +231,59 @@ PreviewCapture :: (media: *FigureMedia, backdrops: *PreviewBackdrops, library: * VecFree(picture.pixels) } failed: s32 - for index: 0..count - 1 { - shot := shots[index] - moment := PreviewSample(library, shot.practice, shot.item, shot.seconds) - // Lying figures need a landscape picture. - width: s32 = ifx shot.practice == PREVIEW_ASTRAL then 900 else 600 - height: s32 = ifx shot.practice == PREVIEW_ASTRAL then 600 else 800 - view := PreviewViewOf(*moment, 0.0, 0.0, 1.0) - for variant: 0..2 { - style := FigureStyleDefault() - style.watercolor = variant == 0 - suffix := ".png" - if variant == 1 { - suffix = "-bare.png" - } else if variant == 2 { - suffix = "-current.png" + written: s32 + suffixes: [5]string = .[".png", "-studio.png", "-male.png", "-male-studio.png", "-current.png"] + for character: cast(s32)0..1 { + // Each character prepares its own painters. + FigurePainterRelease(*body) + FigurePainterRelease(*twin) + for index: 0..count - 1 { + shot := shots[index] + moment := PreviewSample(library, shot.practice, shot.item, shot.seconds) + // Lying figures need a landscape picture. + width: s32 = ifx shot.practice == PREVIEW_ASTRAL then 900 else 600 + height: s32 = ifx shot.practice == PREVIEW_ASTRAL then 600 else 800 + view := PreviewViewOf(*moment, shot.turn, 0.0, 1.0) + if shot.portrait { + view.center = FigureAdd(moment.body.neck, FigureV3(0.0, 0.10, 0.0)) + view.height = 0.42 + view.pitch = 0.05 } - stem: [1024]u8 - named: [1024]u8 - path: [1024]u8 - name := PreviewJoin(stem[:], directory, "/") - name = PreviewJoin(named[:], name, shot.name) - final := PreviewJoin(path[:], name, suffix) - painted := false - if variant == 2 { - camera := PreviewFlatOf(*moment, view) - painted = PreviewFlatRender(camera, view, width, height, *picture) - PreviewOnPaper(*picture) - } else { - painted = PreviewCompose(*body, *twin, media, backdrops, shot.practice, *moment, view, style, - width, height, *picture) - } - if !painted { - print("figure capture: % could not be painted\n", final) - failed += 1 - continue - } - if !WritePNGFile(final, *picture, false) { - print("figure capture: could not write %\n", final) - failed += 1 + for variant: 0..2 { + if variant == 2 && (character != 0 || shot.portrait) { + continue + } + suffix := suffixes[ifx variant == 2 then 4 else character * 2 + variant] + stem: [1024]u8 + named: [1024]u8 + path: [1024]u8 + name := PreviewJoin(stem[:], directory, "/") + name = PreviewJoin(named[:], name, shot.name) + final := PreviewJoin(path[:], name, suffix) + painted := false + if variant == 2 { + camera := PreviewFlatOf(*moment, view) + painted = PreviewFlatRender(camera, view, width, height, *picture) + PreviewOnPaper(*picture) + } else { + media := ifx character == 0 then woman else man + painted = PreviewCompose(*body, *twin, media, backdrops, shot.practice, *moment, view, + FigureStyleDefault(), variant == 1, width, height, *picture) + } + if !painted { + print("figure capture: % could not be painted\n", final) + failed += 1 + continue + } + if !WritePNGFile(final, *picture, false) { + print("figure capture: could not write %\n", final) + failed += 1 + } + written += 1 } } } - print("figure capture: % frames, gpu=% %\n", count * 3, body.accelerated, body.diagnostic) + print("figure capture: % frames, gpu=% %\n", written, body.accelerated, body.diagnostic) return failed } diff --git a/design/figure-preview/preview_profile.zi b/design/figure-preview/preview_profile.zi index 1a0647c75..e2c3f8fcc 100644 --- a/design/figure-preview/preview_profile.zi +++ b/design/figure-preview/preview_profile.zi @@ -60,7 +60,7 @@ PreviewProfileReport :: (label: string) { if count == 0 { return } - names: [PREVIEW_PHASES]string = .["frame", "solve", "pose", "skin", "cloth", "render+readback", "finish", + names: [PREVIEW_PHASES]string = .["frame", "solve", "pose", "skin", "cloth+normals", "render+readback", "fade", "shadow", "backdrop", "over", "twin", "upload", "controls"] print("figure preview timing, %, % frames (median / p95 ms):", label, count) for phase: 0..PREVIEW_PHASES - 1 { diff --git a/design/figure-preview/ziran.lock b/design/figure-preview/ziran.lock index e7a8ac217..b38442532 100644 --- a/design/figure-preview/ziran.lock +++ b/design/figure-preview/ziran.lock @@ -37,15 +37,6 @@ "source": true, "url": "https://github.com/webmproject/libwebp.git" }, - { - "commit": "8e44f3f86262924f513b28cc807e67b1138e5e0b", - "dependencies": {"audio": "p59deb49c7f103127", "avif": "pb203529d803e73a4", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db", "libwebp": "p3b3c785a0e17e605", "sdl3": "p16cd0434af3dff7b", "webp": "p2af20e0c835b1c63"}, - "dependency_refs": {"audio": "1b2f35b7b39df6fb9af7a52324b4b7cf18e98df2", "avif": "2611e727e226a2af22dfb7f10bf224bd2f1a3d30", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339", "sdl3": "829a65d769d935c4852f8159e964312c0957260a", "webp": "ec6ed304767e10c125ab2820f3b01d6fd773e147"}, - "id": "p54dafccfa152a22e", - "name": "kryon", - "ref": "8e44f3f86262924f513b28cc807e67b1138e5e0b", - "url": "https://github.com/kryonlabs/kryon.git" - }, { "commit": "1aadfad932c98c069a1204261b1856f81f3bc199", "dependencies": {}, @@ -73,6 +64,15 @@ "ref": "bd278217e2bac754d868b3d6502eac4257658d4b", "url": "https://github.com/ziranlang/av1.git" }, + { + "commit": "7797a280a89e31e4a5d264c4a9623c2bd3353509", + "dependencies": {"kryon": "p7134544230dacade"}, + "dependency_refs": {"kryon": "4b79d9761508068e901879eb6208a22b8c331a63"}, + "id": "p66b7cac3c445eab0", + "name": "practices", + "ref": "7797a280a89e31e4a5d264c4a9623c2bd3353509", + "url": "https://github.com/waozixyz/practices.git" + }, { "commit": "360553150917f352e49e1beb78917370792ccaef", "dependencies": {}, @@ -81,6 +81,15 @@ "ref": "360553150917f352e49e1beb78917370792ccaef", "url": "https://github.com/ziranlang/image-codec.git" }, + { + "commit": "4b79d9761508068e901879eb6208a22b8c331a63", + "dependencies": {"audio": "p59deb49c7f103127", "avif": "pb203529d803e73a4", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db", "libwebp": "p3b3c785a0e17e605", "sdl3": "p16cd0434af3dff7b", "webp": "p2af20e0c835b1c63"}, + "dependency_refs": {"audio": "1b2f35b7b39df6fb9af7a52324b4b7cf18e98df2", "avif": "2611e727e226a2af22dfb7f10bf224bd2f1a3d30", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339", "sdl3": "829a65d769d935c4852f8159e964312c0957260a", "webp": "ec6ed304767e10c125ab2820f3b01d6fd773e147"}, + "id": "p7134544230dacade", + "name": "kryon", + "ref": "4b79d9761508068e901879eb6208a22b8c331a63", + "url": "https://github.com/kryonlabs/kryon.git" + }, { "commit": "b141d9c45db236335351c8a4b2a14b3ade27c937", "dependencies": {}, @@ -116,20 +125,11 @@ "ref": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6", "source": true, "url": "https://github.com/xiph/opus.git" - }, - { - "commit": "e0950d9379e93dbc3526130588bc6f4bffa170d2", - "dependencies": {"kryon": "p54dafccfa152a22e"}, - "dependency_refs": {"kryon": "8e44f3f86262924f513b28cc807e67b1138e5e0b"}, - "id": "peccdcd876aad0aba", - "name": "practices", - "ref": "e0950d9379e93dbc3526130588bc6f4bffa170d2", - "url": "https://github.com/waozixyz/practices.git" } ], "root": { - "dependencies": {"kryon": "p54dafccfa152a22e", "practices": "peccdcd876aad0aba"}, - "dependency_refs": {"kryon": "8e44f3f86262924f513b28cc807e67b1138e5e0b", "practices": "e0950d9379e93dbc3526130588bc6f4bffa170d2"}, + "dependencies": {"kryon": "p7134544230dacade", "practices": "p66b7cac3c445eab0"}, + "dependency_refs": {"kryon": "4b79d9761508068e901879eb6208a22b8c331a63", "practices": "7797a280a89e31e4a5d264c4a9623c2bd3353509"}, "name": "figure_preview" }, "toolchain": { diff --git a/design/figure-preview/ziran.toml b/design/figure-preview/ziran.toml index c2cc05598..9f2ffe09d 100644 --- a/design/figure-preview/ziran.toml +++ b/design/figure-preview/ziran.toml @@ -10,9 +10,9 @@ ref = "7fbc8152b0ab18b641a73d16d93ccda1e1c7f863" [dependencies.kryon] git = "https://github.com/kryonlabs/kryon.git" -ref = "8e44f3f86262924f513b28cc807e67b1138e5e0b" +ref = "4b79d9761508068e901879eb6208a22b8c331a63" # The shared figure and its media (anatomy, textures, Tai Chi course). [dependencies.practices] git = "https://github.com/waozixyz/practices.git" -ref = "e0950d9379e93dbc3526130588bc6f4bffa170d2" +ref = "7797a280a89e31e4a5d264c4a9623c2bd3353509" diff --git a/plans/2026-11-17-astral-projection.md b/plans/2026-11-17-astral-projection.md index 05bb57d7e..0154af4a3 100644 --- a/plans/2026-11-17-astral-projection.md +++ b/plans/2026-11-17-astral-projection.md @@ -1,57 +1,57 @@ -# Open practice figure work — 2026-11-17 +# Open practice figure work — 2026-11-18 -The owner wants one perfected character used everywhere: Tai Chi, Sun +The owner wants the practice figures used everywhere: Tai Chi, Sun Salutation, Workout and astral projection, native on Ziran and Kryon -without raylib: a slim, cute young Chinese woman with sleek black hair, an -attractive Chinese-style practice outfit, matched to Inner Breeze's own -storybook illustrations with only a little texture, and vivid colour. The -character is the practices package's `figure/`; its style target is -practices `figure/design/reference/style-target.webp`, made from the Tai Chi -banner. The live tuning tool is `design/figure-preview/` (see its README). -The three.js studies in `design/astral-projection/three/` are look -references only. +without raylib. They must look as good as the owner's reference sculptures +(practices `figure/design/reference/`): correct proportions, smooth +surfaces, clean colours, no paint, paper or grain. The default is a petite +young Chinese woman with black hair, smooth skin and an attractive Chinese +outfit; a young man in a kung fu outfit is the second character, to be +offered as a choice. Breeze colours and backdrops stay. The characters are +the practices package's `figure/`; the live tuning tool is +`design/figure-preview/` (see its README). The three.js studies in +`design/astral-projection/three/` are look references only. -- Kryon, owned by the Kryon lanes: the first-frame sampler-unit clobber in - `scene_gpu.zi` (the figure paints its first picture twice) and the - per-frame geometry rebuild (every moving frame re-expands all triangles - into a new vertex buffer and re-uploads it, about 5–6 ms on llvmpipe); - then repin and remove the workaround. Images still compare by texture id - only, so the preview alternates two textures. -- Owner review of the live preview and of - `build/practice-compare/side-by-side/` (current flat figure beside the new - character, same moments and cameras), then tune from that feedback. +- Owner review of the live preview, of the reference comparisons in + `build/practice-compare/reference/` and of the before/after side-by-sides + in `build/practice-compare/side-by-side/`; tune from that feedback. +- Better base mesh once Kryon's glTF importer lands (the Kryon task + codex-kryon-kryon-idle-present-fix has it queued): a properly licensed + higher-resolution base (MakeHuman/MPFB CC0 with a high-res proxy, or + another CC0/CC-BY model with its licence recorded in practices + `figure/design/`), chosen by how close it comes to the references. Never + use ripped game models (the owner's Character-14.zip is one). - Character work still open: - - The top's lower part swings rigidly from the waist and only by the + - The jacket's skirt swings rigidly from the waist and only by the pelvis's tilt; secondary sway and a simple collision with the thighs would help in deep squats and folds. - - The face painting is projected from the front; in profile its side - fades to plain skin. - - The cream piping at the top's hem and cuffs in the style target is not - painted yet. - - The asset bake (cloth shells, UVs, texture swatches) is Python in - `scripts/prepare-practice-human.py`; port it to Ziran with the anatomy - reader. + - The face map is projected from the front; in profile its side fades + to plain skin. + - No ambient occlusion yet: crevices (armpits, under the bun, between the + legs) are lit like open surfaces. Bake it per vertex once the vertex + format has room, or add it to Kryon's material. + - The asset bake (shapes, clothes, hair, UVs, texture maps, the face) is + Python in `scripts/prepare-practice-human.py`; port it to Ziran with the + anatomy reader. - Astral session timings: practices' `astral_projection/sessions/*.json` are another task's uncommitted files. Until they are pushed, a pinned preview plays the six techniques with steps evenly 20 seconds apart. - Breeze adoption, after the shared Kryon repin (lane -7, plot, entity, game2d, css and apps on one Kryon; Breeze audio on Ziran std audio): - - Make Breeze's `practices` dependency a package pinned at or after - 3e7c7bff. + - Make Breeze's `practices` dependency a package pinned at or after the + commit that has both characters. - Move `PreviewJoints` (solver joints to `FigureJoints`) beside the solver. - Paint Tai Chi, Sun Salutation, Workout and astral with `FigurePaint` under `DESKTOP_HOST`, keeping timelines, cues, narration, pause/resume - and history. Bundle `assets/practices/shared/watercolor/` from the - common Practices pack (the `scripts/prepare-package-assets.py` hunk is - ready). + and history, with a setting for the woman or the man. Bundle + `assets/practices/shared/figure/` from the common Practices pack. - Native app after-frames for those painters, matching `build/practice-compare/before/`. Retake the full-form before frame: it shows the voice-guidance offer instead of the figure. -- Performance: the painter re-skins and re-finishes on every pose change - (the wash finish, ground shadow and backdrop on the CPU, about 20k - vertices skinned on the CPU). Measure on a real phone GPU; shell GL here - is llvmpipe. +- Performance: measure on a real phone GPU; shell GL here is llvmpipe. + The figure re-skins and recomputes normals for about 17k vertices on the + CPU every moving frame. - Narration: the initial audit found all 88 cue texts in each of ten locales but only 407/880 female clips (cs 6, de 86, en 86, es 78, fr 37, ja 5, ko 6, pt 88, ru 10, zh 5). Complete and listen through the owning diff --git a/scripts/prepare-practice-human.py b/scripts/prepare-practice-human.py index 4d194e1b3..c1350b85a 100644 --- a/scripts/prepare-practice-human.py +++ b/scripts/prepare-practice-human.py @@ -1,5 +1,13 @@ #!/usr/bin/env python3 -"""Bake the pinned CC0 MakeHuman surface for the native practice skin rig.""" +"""Bake a practice character from the pinned CC0 MakeHuman surface: its +shape, rig, clothes, hair and clean texture maps, for practices' figure. + + prepare-practice-human.py --output practices/shared/figure --character female + prepare-practice-human.py --output practices/shared/figure --character male + prepare-practice-human.py --output practices/shared/figure --backdrops + +Each character goes to OUTPUT/CHARACTER: anatomy.bin (PFIG0002), its texture +maps and anatomy.json. The backdrops come from OUTPUT/source.""" import argparse import gzip import hashlib @@ -9,76 +17,63 @@ import struct import numpy as np ROOT = Path(__file__).resolve().parents[1] - -# The painted textures and backdrops come from generated watercolor -# originals kept in OUTPUT/source (provenance.json there): each swatch is -# moved to the style target's palette, made to tile without a seam and -# sized for phones. -SWATCHES = {'skin': ('#f3d2b8', 0.45), 'top': ('#3f9a7e', 0.9), 'trousers': ('#24345e', 0.85), - 'hair': ('#1e1e28', 1.0)} +ASSETS = ROOT/'design/astral-projection/three/assets' BACKDROPS = ('tai-chi', 'sun-salutation', 'workout', 'astral') -def prepare_textures(folder): +CHARACTERS = { + # A petite young Chinese woman, slim and toned: narrow shoulders, small + # hands and feet and a small soft jaw. A fitted jade top with cap sleeves, + # a stand-up collar and frog knots, slim navy trousers, bare feet; sleek + # black hair parted in the middle and drawn back into a high bun. + 'female': dict(gender='female', races=(('asian', 0.9), ('caucasian', 0.1)), + weight=0.10, muscle=0.45, height=0.60, hands=0.86, feet=0.88, neck=0.006, + shoulders=0.012, jaw=0.08, eyes=0.22, mouth=0.10, chin=0.07, outfit='fitted', hair='bun', + colours=dict(skin='#f5d7c3', top='#2aa385', trousers='#283b70', hair='#231f27', + knot='#f4e8cc', iris='#3b2418', lashes='#140f0e', brows='#3d2c25', + lips='#e3788a', blush='#f4a3a5')), + # A young Chinese man, athletic. A loose indigo kung fu jacket with a + # stand-up collar and frog knots down the front, wide black trousers + # gathered at the ankle, bare feet; short black hair. + 'male': dict(gender='male', races=(('asian', 0.9), ('caucasian', 0.1)), + weight=0.40, muscle=0.65, height=0.60, hands=0.98, feet=0.98, neck=0.004, + shoulders=0.0, jaw=0.0, eyes=0.04, mouth=0.0, chin=0.0, outfit='kungfu', hair='short', + colours=dict(skin='#ecc7a9', top='#36508f', trousers='#25252d', hair='#1e1b20', + knot='#f0e3c6', iris='#2e1d14', lashes='#1a1311', brows='#211813', + lips='#c98b85', blush=None)), +} + + +def colour(text): + return np.array([int(text[at:at+2], 16) for at in (1, 3, 5)], dtype=np.float64) + + +def prepare_backdrops(folder): from PIL import Image - source = folder/'source' - for name, (target, contrast) in SWATCHES.items(): - picture = np.asarray(Image.open(source/f'{name}.webp').convert('RGB').resize((512, 512), Image.LANCZOS), - dtype=np.float64) - mean = picture.reshape(-1, 3).mean(axis=0) - goal = np.array([int(target[at:at+2], 16) for at in (1, 3, 5)], dtype=np.float64) - light = picture @ np.array([0.30, 0.59, 0.11]) - # Keep the brushwork's light and dark, painted in the target colour, - # with a little of the swatch's own colour variation. - shade = (light-light.mean())*contrast - tinted = goal+shade[:, :, None]+(picture-mean-(light-light.mean())[:, :, None])*0.45 - # A copy offset by half covers the seam at the edges. - shifted = np.roll(tinted, (256, 256), axis=(0, 1)) - ramp = 1-np.abs(np.arange(512)/511*2-1) - weight = np.clip(np.minimum.outer(ramp, ramp)*3, 0, 1)[:, :, None] - tiled = tinted*weight+shifted*(1-weight) - Image.fromarray(np.clip(tiled, 0, 255).astype(np.uint8)).save(folder/f'{name}.webp', quality=88, method=6) - # The face painting takes the skin swatch's colour on its cheeks and - # brow, keeping its own eyes, brows, lips and blush. - # The trim keeps its own colours: jade silk with cream frog knots. - Image.open(source/'trim.webp').convert('RGB').resize((256, 256), Image.LANCZOS).save( - folder/'trim.webp', quality=90, method=6) - face = np.asarray(Image.open(source/'face.webp').convert('RGB').resize((512, 512), Image.LANCZOS), dtype=np.float64) - skin = face[135:170, 228:286].reshape(-1, 3).mean(axis=0) - goal = np.array([int(SWATCHES['skin'][0][at:at+2], 16) for at in (1, 3, 5)], dtype=np.float64) - face = face*goal/skin - # The paper beside her small chin becomes skin too, where MakeHuman's - # wider jaw reaches past the painted one; her hair, eyes and lips stay. - light = face @ np.array([0.30, 0.59, 0.11]) - warmth = face[:, :, 0]-face[:, :, 2] - paper = np.clip((light-205)/20, 0, 1)*np.clip((48-warmth)/14, 0, 1) - face = face*(1-paper[:, :, None])+goal*paper[:, :, None] - # Outside the painted face (its paper, hair and ears) the painting - # becomes plain skin, so wherever the mesh's face reaches past it the - # skin goes on. - y, x = np.mgrid[0:512, 0:512] - oval = np.sqrt(((x-257)/140)**2+((y-250)/175)**2) - keep = np.clip((1.0-oval)/0.18, 0, 1)[:, :, None] - face = face*keep+goal*(1-keep) - Image.fromarray(np.clip(face, 0, 255).astype(np.uint8)).save(folder/'face.webp', quality=90, method=6) (folder/'backdrops').mkdir(exist_ok=True) for name in BACKDROPS: - picture = Image.open(source/f'backdrop-{name}.webp').convert('RGB') + picture = Image.open(folder/'source'/f'backdrop-{name}.webp').convert('RGB') picture.thumbnail((1280, 1280), Image.LANCZOS) - # Richer washes; the near-white paper barely moves. + # Richer colour; the near-white sky barely moves. pixels = np.asarray(picture, dtype=np.float64) light = (pixels @ np.array([0.30, 0.59, 0.11]))[:, :, None] pixels = np.clip(light+(pixels-light)*1.3, 0, 255) Image.fromarray(pixels.astype(np.uint8)).save(folder/'backdrops'/f'{name}.webp', quality=85, method=6) -parser = argparse.ArgumentParser(description=__doc__) + +parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--output', type=Path, required=True) -parser.add_argument('--textures-only', action='store_true', - help='only rebuild the painted textures and backdrops from OUTPUT/source') +parser.add_argument('--character', choices=sorted(CHARACTERS)) +parser.add_argument('--backdrops', action='store_true', help='only rebuild the backdrops from OUTPUT/source') args = parser.parse_args() -if args.textures_only: - prepare_textures(args.output.resolve()) +if args.backdrops: + prepare_backdrops(args.output.resolve()) raise SystemExit(0) -source_file = ROOT / 'design/astral-projection/three/assets/makehuman-base.obj.gz' +if args.character is None: + parser.error('--character is required unless --backdrops') +spec = CHARACTERS[args.character] +gender = spec['gender'] + +source_file = ASSETS/'makehuman-base.obj.gz' vertices, groups, group = [], {}, '' for line in gzip.open(source_file, 'rt'): if line.startswith('v '): @@ -89,36 +84,46 @@ for line in gzip.open(source_file, 'rt'): elif line.startswith('f '): groups[group].append([int(item.split('/')[0]) - 1 for item in line.split()[1:]]) all_vertices = np.asarray(vertices, dtype=np.float64) -# MakeHuman's base mesh is its gender-neutral average. She is a slim young -# Chinese woman: MakeHuman's own CC0 young-adult female macro shape, mostly -# its Asian target, with the weight slider at 0.15, muscle at 0.30, height -# at 0.65 and ideal proportions, mixed as MakeHuman mixes its macro targets -# (each weight-and-muscle pair by the product of their shares). + + +# MakeHuman's base mesh is its gender-neutral average. Each character is +# MakeHuman's own CC0 young-adult macro shape for its gender, mostly its +# Asian target, at its weight, muscle and height with ideal proportions, +# mixed as MakeHuman mixes its macro targets (each weight-and-muscle pair by +# the product of their shares). def apply_target(name, share): - target = ROOT / f'design/astral-projection/three/assets/makehuman-{name}.target.gz' - for line in gzip.open(target, 'rt'): + if share == 0.0: + return + for line in gzip.open(ASSETS/f'makehuman-{name}.target.gz', 'rt'): if line.strip() and not line.startswith('#'): index, dx, dy, dz = line.split() all_vertices[int(index)] += np.array([float(dx), float(dy), float(dz)])*share -for race, share in (('asian', 0.9), ('caucasian', 0.1)): - apply_target(f'{race}-female-young', share) -BODY_WEIGHT, BODY_MUSCLE, BODY_HEIGHT, BODY_PROPORTIONS = 0.15, 0.30, 0.65, 1.0 -for muscle, muscle_share in (('minmuscle', 1-BODY_MUSCLE/0.5), ('averagemuscle', BODY_MUSCLE/0.5)): - for weight, weight_share in (('minweight', 1-BODY_WEIGHT/0.5), ('averageweight', BODY_WEIGHT/0.5)): + +def bracket(value): + if value <= 0.5: + return (('min', 1-value/0.5), ('average', value/0.5)) + return (('average', 1-(value-0.5)/0.5), ('max', (value-0.5)/0.5)) + + +for race, share in spec['races']: + apply_target(f'{race}-{gender}-young', share) +for muscle, muscle_share in bracket(spec['muscle']): + for weight, weight_share in bracket(spec['weight']): pair = muscle_share*weight_share - if (muscle, weight) != ('averagemuscle', 'averageweight'): - apply_target(f'universal-female-young-{muscle}-{weight}', pair) - apply_target(f'proportions-female-young-{muscle}-{weight}-idealproportions', pair*BODY_PROPORTIONS) + if (muscle, weight) != ('average', 'average'): + apply_target(f'universal-{gender}-young-{muscle}muscle-{weight}weight', pair) + apply_target(f'proportions-{gender}-young-{muscle}muscle-{weight}weight-idealproportions', pair) # MakeHuman's four maxheight targets for these pairs are the same file. -apply_target('height-female-young-maxheight', (BODY_HEIGHT-0.5)/0.5) +apply_target(f'height-{gender}-young-maxheight', max(spec['height']-0.5, 0.0)/0.5) # MakeHuman's own CC0 rig weights for this mesh (folded onto this figure's -# bones further on). -weights_file = ROOT / 'design/astral-projection/three/assets/makehuman-default-weights.mhw.gz' -rig = json.loads(gzip.open(weights_file, 'rt').read()) +# bones further on). They cover its joint helpers too, so a shape change +# weighted by them carries the rig along. +rig = json.loads(gzip.open(ASSETS/'makehuman-default-weights.mhw.gz', 'rt').read()) assert rig['license'] == 'CC0' + def rig_share(accept): share = np.zeros(len(all_vertices)) for name, entries in rig['weights'].items(): @@ -127,32 +132,77 @@ def rig_share(accept): share[vertex] += weight return np.clip(share, 0, 1) + def helpers(prefix): return sorted({index for group, faces in groups.items() if group.startswith(prefix) for face in faces for index in face}) + def group_centre(name): return all_vertices[sorted({index for face in groups['joint-'+name] for index in face})].mean(axis=0) -# Graceful hands and feet: each a little smaller about the wrist or ankle, -# with its finger and toe joints, so the rig still fits. + +def smooth(value): + value = np.clip(value, 0, 1) + return value*value*(3-2*value) + + metres = 1.7/np.ptp(all_vertices[sorted({i for f in groups['body'] for i in f})][:, 1]) for side in ('L', 'R'): prefix = 'l' if side == 'L' else 'r' - for pivot_name, stems, joint_prefix, factor in ( - ('hand', ('wrist', 'metacarpal', 'finger'), f'joint-{prefix}-finger', 0.90), - ('ankle', ('foot', 'toe'), f'joint-{prefix}-toe', 0.92)): + # Graceful hands and feet: each a little smaller about the wrist or ankle. + for pivot_name, stems, factor in (('hand', ('wrist', 'metacarpal', 'finger'), spec['hands']), + ('ankle', ('foot', 'toe'), spec['feet'])): pivot = group_centre(f'{prefix}-{pivot_name}') share = rig_share(lambda name: name.endswith('.'+side) and name.split('.')[0].startswith(stems)) all_vertices += (pivot-all_vertices)*((1-factor)*share)[:, None] - tips = helpers(joint_prefix) - all_vertices[tips] = pivot+(all_vertices[tips]-pivot)*factor + # Narrower shoulders: each arm moves in towards her, the collarbone half + # as far. + if spec['shoulders']: + arm = rig_share(lambda name: name.endswith('.'+side) and name.split('.')[0].startswith( + ('shoulder01', 'upperarm', 'lowerarm', 'wrist', 'metacarpal', 'finger'))) + collar_bone = rig_share(lambda name: name == 'clavicle.'+side) + inward = 1.0 if side == 'L' else -1.0 + all_vertices[:, 0] -= inward*np.clip(arm+0.5*collar_bone, 0, 1)*spec['shoulders']/metres # A longer neck: everything the head carries rises a little, fading in up # the neck and away from the shoulders. neck_base, skull = group_centre('neck'), group_centre('head') rise = np.clip((all_vertices[:, 1]-neck_base[1])/(skull[1]-neck_base[1]), 0, 1) rise = rise*rise*(3-2*rise)*np.clip(1-(np.abs(all_vertices[:, 0])-0.05/metres)/(0.05/metres), 0, 1) -all_vertices[:, 1] += rise*0.014/metres +all_vertices[:, 1] += rise*spec['neck']/metres +# A small soft jaw: the face narrows a little from the cheekbones to the +# chin, and the neck under it with it. +if spec['jaw']: + eye_level = group_centre('l-eye')[1] + down = smooth((eye_level-all_vertices[:, 1])/(0.075/metres)) + above_shoulders = smooth((all_vertices[:, 1]-(eye_level-0.135/metres))/(0.03/metres)) + near = np.abs(all_vertices[:, 0]) < 0.1/metres + all_vertices[:, 0] *= 1-spec['jaw']*down*above_shoulders*near +eye_level = group_centre('l-eye')[1] +for prefix in ('l', 'r'): + # Larger eyes, opened a little more than widened, fading out round each + # eye; the eyeball itself grows evenly. + centre = group_centre(f'{prefix}-eye') + offset = all_vertices-centre + reach = np.linalg.norm(offset, axis=1)/(0.026/metres) + grow = spec['eyes']*smooth(1-reach)**2 + ball = helpers(f'helper-{prefix}-eye') + factor = np.column_stack((1+0.8*grow, 1+1.3*grow, 1+0.6*grow)) + factor[ball] = 1+spec['eyes']*0.75 + all_vertices = centre+offset*factor +mouth_centre = group_centre('mouth') +if spec['mouth']: + # A smaller mouth: the lips draw in towards their middle. + offset = all_vertices-mouth_centre + near = smooth(1-np.linalg.norm(offset[:, :2], axis=1)/(0.035/metres))*(offset[:, 2] > -0.01/metres) + all_vertices[:, 0] -= offset[:, 0]*spec['mouth']*near +if spec['chin']: + # A shorter lower face: from below the nose to the chin it rises a + # little towards the eyes, the neck under it following less and less. + below = smooth((eye_level-0.035/metres-all_vertices[:, 1])/(0.04/metres)) + above_neck = smooth((all_vertices[:, 1]-(eye_level-0.16/metres))/(0.035/metres)) + near = np.abs(all_vertices[:, 0]) < 0.1/metres + all_vertices[:, 1] += (eye_level-0.035/metres-all_vertices[:, 1])*spec['chin']*below*above_neck*near ids = sorted({index for face in groups['body'] for index in face}) lookup = {old: index for index, old in enumerate(ids)} body = all_vertices[ids] @@ -160,18 +210,26 @@ scale = 1.7 / np.ptp(body[:, 1]) origin = np.array([0, body[:, 1].min(), 0]) positions = (body - origin) * scale + def joint(name): indices = sorted({index for face in groups['joint-' + name] for index in face}) return (all_vertices[indices].mean(axis=0) - origin) * scale + +def helper_points(name): + return (all_vertices[sorted({index for face in groups[name] for index in face})]-origin)*scale + + bones = [] + def bone(role, side, start, end, parent=-1, finger=0, segment=0): index = len(bones) bones.append(dict(role=role, side=side, origin=np.array(start), tip=np.array(end), parent=parent, finger=finger, segment=segment)) return index + # The arm and finger chains match the preview's anatomical joints; native # standing and floor practices also need the pelvis, spine, head and legs. bone(0, 0, joint('pelvis'), joint('spine-3')) @@ -206,7 +264,6 @@ weights = np.zeros((len(ids), 4), dtype=np.float64) joints = np.zeros((len(ids), 4), dtype=np.uint8) for index, point in enumerate(positions): side = 0 if point[0] >= 0 else 1 - shoulder = joint(('l' if side == 0 else 'r') + '-shoulder') hip = joint(('l' if side == 0 else 'r') + '-upper-leg') candidates = list(range(4)) + arm_sets[side] # Blend branch eligibility across the torso instead of cutting the mesh @@ -232,6 +289,7 @@ for index, point in enumerate(positions): joints[index, :len(order)] = np.asarray(candidates)[order] weights[index, :len(order)] = raw + # MakeHuman's own CC0 rig weights for this mesh, folded onto these 46 bones. # The procedural weights above remain only for vertices the rig leaves out. def rig_bones(name): @@ -263,6 +321,7 @@ def rig_bones(name): return [(base+20, 1.0)] return [(3, 1.0)] # neck, head, jaw, eyes and face + for index, (at, side) in enumerate(((0, 0), (0, 1))): assert bones[4+side*21]['role'] == 4 and bones[4+side*21+18]['role'] == 8 gathered = [dict() for _ in ids] @@ -299,6 +358,7 @@ for slot in range(4): np.add.at(dense, (np.arange(len(ids)), joints[:, slot]), weights[:, slot]) arm_share = dense[:, [at for at, item in enumerate(bones) if 5 <= item['role'] <= 7]].sum(axis=1) + def diffuse(members, zone, steps): shares = dense[:, members] mass = shares.sum(axis=1) @@ -312,6 +372,7 @@ def diffuse(members, zone, steps): shares[active] = mixed[active]*scale[active, None] dense[:, members] = shares + hips_y = (joint('l-upper-leg')[1]+joint('r-upper-leg')[1])/2 hip_zone = (positions[:, 1] > hips_y-0.24) & (positions[:, 1] < hips_y+0.07) & (arm_share < 0.01) thighs = [4+18, 4+21+18] @@ -343,40 +404,51 @@ assert not np.any(arm_roles[joints[waist]] & (weights[waist] > 0)), 'Waist canno hands = (np.abs(positions[:, 0]) > 0.40) & (positions[:, 2] > 0.20) assert np.all(np.sum(weights[hands] * (joints[hands] < 4), axis=1) < 0.1), 'Fingers cannot follow the trunk' -triangles = [] -for face in groups['body']: - for index in range(1, len(face)-1): - triangles.append([lookup[face[0]], lookup[face[index]], lookup[face[index+1]]]) -triangles = np.array(triangles, dtype=np.int64) -normals = np.zeros_like(positions) -face_normals = np.cross(positions[triangles[:, 1]]-positions[triangles[:, 0]], - positions[triangles[:, 2]]-positions[triangles[:, 0]]) -for corner in range(3): - np.add.at(normals, triangles[:, corner], face_normals) -normals /= np.maximum(np.linalg.norm(normals, axis=1)[:, None], 1e-12) -uvs = np.column_stack((positions[:, 0]*3+0.5, positions[:, 1]*3)) -# Regions keep the same surface and skin weights: skin, tunic, trousers, hair. +triangles = face_triangles.copy() + + +def vertex_normals(vertices, faces): + result = np.zeros_like(vertices) + face = np.cross(vertices[faces[:, 1]]-vertices[faces[:, 0]], vertices[faces[:, 2]]-vertices[faces[:, 0]]) + for corner in range(3): + np.add.at(result, faces[:, corner], face) + return result/np.maximum(np.linalg.norm(result, axis=1)[:, None], 1e-12) + + +normals = vertex_normals(positions, triangles) +# Regions keep the same surface and skin weights: skin, top, trousers, hair. hip_height = joint('pelvis')[1] neck_height = joint('neck')[1] -head = joint('head') +hips_joint = (joint('l-upper-leg')+joint('r-upper-leg'))/2 cuffs = [abs(joint(prefix+'-hand')[0])-0.025 for prefix in ('l', 'r')] ankles = [joint(prefix+'-ankle')[1]+0.02 for prefix in ('l', 'r')] - eye_height = joint('l-eye')[1] +head_centre_z = joint('head')[2] +fitted = spec['outfit'] == 'fitted' +# Her fitted top ends just over the hips; his jacket's body region ends at +# the trouser waist and its skirt hangs on below. +top_hem = hips_joint[1]+0.01 if fitted else hip_height-0.04 +HAIRLINES = {'bun': [0.050, 0.050, 0.045, 0.031, 0.012, 0.000, -0.022, -0.045], + 'short': [0.056, 0.063, 0.060, 0.036, 0.012, 0.000, -0.022, -0.042]} + + +def head_turn(points): + return np.degrees(np.arctan2(np.abs(points[:, 0]), points[:, 2]-0.02)) + def hairline(points): - """Positive on the hair: a hairline high on the forehead, lower over - the temples, behind the ears and down to the nape; the ears stay bare.""" + """Positive on the hair: from the hairline over the forehead, the temples, + behind the ears and down to the nape; the ears stay bare.""" points = np.atleast_2d(points) x, y, z = points[:, 0], points[:, 1], points[:, 2] - turn = np.degrees(np.arctan2(np.abs(x), z-0.02)) - height = eye_height+np.interp(turn, [0, 20, 45, 65, 85, 105, 125, 180], - [0.056, 0.055, 0.047, 0.030, 0.010, 0.000, -0.022, -0.045]) + turn = head_turn(points) + height = eye_height+np.interp(turn, [0, 20, 45, 65, 85, 105, 125, 180], HAIRLINES[spec['hair']]) value = y-height ears = (y < eye_height+0.002) & (np.abs(x) > 0.070) value = np.where(ears, np.minimum(value, 0.070-np.abs(x)), value) return np.where(y < 1.44, -1.0, value) + def neckline(points): """Positive below the mandarin top's round neckline, a little lower in front, where its stand-up collar begins.""" @@ -385,35 +457,76 @@ def neckline(points): front = 0.012*np.clip(1-np.abs(x)/0.07, 0, 1)*np.clip((z-0.02)/0.04, 0, 1) return (neck_height-0.008-front)-y + +def arm_points(points): + """The arms in the bind pose: near the shoulder-elbow-hand line, out from + the trunk.""" + points = np.atleast_2d(points) + result = np.zeros(len(points), dtype=bool) + for prefix in ('l', 'r'): + s, e, h = joint(prefix+'-shoulder'), joint(prefix+'-elbow'), joint(prefix+'-hand') + mine = (points[:, 0] >= 0) == (prefix == 'l') + for a, b in ((s, e), (e, h)): + t = np.clip((points-a) @ (b-a)/np.dot(b-a, b-a), 0, 1) + near = np.linalg.norm(points-(a+t[:, None]*(b-a)), axis=1) < 0.075 + result |= mine & near & (np.abs(points[:, 0]) > 0.10) + return result + + +def sleeve_end(points): + """Positive on the arm past her cap sleeves, a third of the way down the + upper arm, across the arm.""" + points = np.atleast_2d(points) + value = np.full(len(points), -1.0) + for prefix in ('l', 'r'): + s, e = joint(prefix+'-shoulder'), joint(prefix+'-elbow') + axis = (e-s)/np.linalg.norm(e-s) + mine = arm_points(points) & ((points[:, 0] >= 0) == (prefix == 'l')) + value[mine] = ((points[mine]-s) @ axis)-0.33*np.linalg.norm(e-s) + return value + + def region_of(points): points = np.atleast_2d(points) x, y, z = points[:, 0], points[:, 1], points[:, 2] regions = np.zeros(len(points), dtype=np.uint8) # Sleeves continue over the shoulder cap. A horizontal collar cutoff alone # leaves isolated bare patches where the arm rises above the neck cutoff. - regions[(y > hip_height-0.09) & ((neckline(points) > 0) | - ((np.abs(x) > 0.115) & (y < neck_height+0.025)))] = 1 - regions[y <= hip_height-0.04] = 2 - for cuff, ankle in zip(cuffs, ankles): - # Hands hang below the hips in the bind pose; only arms reach this wide. - regions[(np.abs(x) > cuff) & (y > 0.5)] = 0 + covered = (y > top_hem) & ((neckline(points) > 0) | ((np.abs(x) > 0.115) & (y < neck_height+0.025))) + if fitted: + arms = arm_points(points) + regions[covered & ~(arms & (sleeve_end(points) > 0))] = 1 + regions[(y <= top_hem) & ~arms] = 2 + else: + regions[covered] = 1 + regions[y <= top_hem] = 2 + for cuff in cuffs: + # Hands hang below the hips in the bind pose; only arms reach this wide. + regions[(np.abs(x) > cuff) & (y > 0.5)] = 0 + for ankle in ankles: regions[y < ankle] = 0 regions[hairline(points) > 0] = 3 return regions -# Clean painted hems: split each triangle that crosses a region boundary -# exactly along the boundary's plane, then give every region its own copy -# of the shared hem vertices. Surface and skin stay continuous. + +# Clean hems: split each triangle that crosses a region boundary exactly +# along the boundary, then give every region its own copy of the shared hem +# vertices. Surface and skin stay continuous. def plane(axis, value): return lambda points: np.atleast_2d(points)[:, axis]-value -planes = [(1, hip_height-0.04), (1, neck_height+0.025), (0, 0.115), (0, -0.115)] -planes += [(0, cuff) for cuff in cuffs] + [(0, -cuff) for cuff in cuffs] + [(1, ankle) for ankle in ankles] + +planes = [(1, top_hem), (1, neck_height+0.025), (0, 0.115), (0, -0.115)] + [(1, ankle) for ankle in ankles] +if not fitted: + planes += [(0, cuff) for cuff in cuffs] + [(0, -cuff) for cuff in cuffs] cuts = [(('plane',)+item, plane(*item)) for item in planes] + [(('neckline',), neckline), (('hairline',), hairline)] +if fitted: + cuts.append((('sleeve',), sleeve_end)) points, skin_joints, skin_weights = list(positions), list(joints), list(weights) surface_normals = list(normals) edges = {} + def hem_point(a, b, name, cut): key = (min(a, b), max(a, b), name) if key not in edges: @@ -433,6 +546,7 @@ def hem_point(a, b, name, cut): edges[key] = len(points)-1 return edges[key] + faces = [list(face) for face in triangles] for name, cut in cuts: split = [] @@ -480,9 +594,10 @@ normals = np.array(surface_normals)[source] joints = np.array(skin_joints)[source] weights = np.array(skin_weights)[source] triangles = np.array(faces, dtype=np.int64) -# The head. MakeHuman's own eyeballs sit in the sockets under painted lids; -# a hair shell rises from nothing at the hairline to a centimetre over the -# crown; a low bun sits at the back. All follow the head bone alone. +role_of = np.array([item['role'] for item in bones]) +head_index = [at for at, item in enumerate(bones) if item['role'] == 3][0] + + def outward_faces(vertices, faces, center): faces = np.array(faces, dtype=np.int64) normal = np.cross(vertices[faces[:, 1]]-vertices[faces[:, 0]], vertices[faces[:, 2]]-vertices[faces[:, 0]]) @@ -490,49 +605,85 @@ def outward_faces(vertices, faces, center): faces[flip] = faces[flip][:, ::-1] return faces -def vertex_normals(vertices, faces): - result = np.zeros_like(vertices) - face = np.cross(vertices[faces[:, 1]]-vertices[faces[:, 0]], vertices[faces[:, 2]]-vertices[faces[:, 0]]) - for corner in range(3): - np.add.at(result, faces[:, corner], face) - return result/np.maximum(np.linalg.norm(result, axis=1)[:, None], 1e-12) +def neighbours(faces, count): + edge = np.concatenate([faces[:, [0, 1]], faces[:, [1, 2]], faces[:, [2, 0]]]) + edge = np.unique(np.concatenate([edge, edge[:, ::-1]]), axis=0) + return edge, np.maximum(np.bincount(edge[:, 0], minlength=count), 1).astype(np.float64) + + +def relax(base, normal, lift, faces, steps, pinned=None): + """Cloth or hair LIFT off the surface BASE, smoothed the way cloth lies: + it bridges hollows (between the breasts, the small of the back, the + crotch) but never sinks below LIFT or slides along the surface. PINNED + vertices keep their lift, so an edge stays on the surface.""" + edge, count = neighbours(faces, len(base)) + height = lift.copy() + for _ in range(steps): + shell = base+normal*height[:, None] + total = np.zeros_like(shell) + np.add.at(total, edge[:, 0], shell[edge[:, 1]]) + towards = np.einsum('ij,ij->i', total/count[:, None]-shell, normal) + height = np.maximum(height+0.5*towards, lift) + if pinned is not None: + height[pinned] = lift[pinned] + return base+normal*height[:, None] + + +# The head. MakeHuman's own eyeballs sit in the sockets under the lids; a +# hair shell rises from nothing at the hairline over the crown. extras = [] +body_count = len(positions) hair_faces = triangles[np.all(regions[triangles] == 3, axis=1)] used = np.unique(hair_faces) -depth = hairline(positions[used]) -# Sleek black hair combed back close to the head, a little fuller -# towards the crown where it gathers into the bun. -top = np.clip((positions[used, 1]-eye_height-0.03)/0.07, 0, 1) -back = np.clip((joint('head')[2]+0.01-positions[used, 2])/0.08, 0, 1) -sides = np.clip(np.abs(positions[used, 0])/0.07, 0, 1) -above = np.clip((positions[used, 1]-eye_height)/0.03, 0, 1) -thickness = (0.004+0.007*top+0.006*top*back+0.004*sides*above)*np.clip(depth/0.03, 0, 1)**0.8 -shell = positions[used]+normals[used]*thickness[:, None] +p = positions[used] +depth = hairline(p) +top = np.clip((p[:, 1]-eye_height-0.03)/0.07, 0, 1) +back = np.clip((head_centre_z+0.01-p[:, 2])/0.08, 0, 1) +sides = np.clip(np.abs(p[:, 0])/0.07, 0, 1) +above = np.clip((p[:, 1]-eye_height)/0.03, 0, 1) +if spec['hair'] == 'bun': + # Sleek, a little fuller towards the crown where it gathers into the bun. + thickness = (0.004+0.006*top+0.005*top*back+0.002*sides*above)*np.clip(depth/0.02, 0, 1)**0.7 +else: + thickness = (0.0035+0.004*top+0.002*back)*np.clip(depth/0.015, 0, 1)**0.8 remap = np.full(len(positions), -1, dtype=np.int64) remap[used] = np.arange(len(used)) shell_faces = remap[hair_faces] +# Its edge stays on the skin at the hairline, with no crack between them. +shell = relax(p, normals[used], thickness, shell_faces, 12, depth <= 0.0005) +if spec['hair'] == 'bun': + # A centre parting from the hairline back over the crown: the hair dips + # to the scalp along a narrow line. + height = np.einsum('ij,ij->i', shell-p, normals[used]) + front = smooth((p[:, 2]-(head_centre_z-0.05))/0.03)*smooth((p[:, 1]-eye_height-0.035)/0.01) + height *= 1-0.8*np.exp(-(p[:, 0]/0.0045)**2)*front + shell = p+normals[used]*height[:, None] extras.append((shell, vertex_normals(shell, shell_faces), np.full(len(shell), 3), shell_faces)) -rings, segments = 10, 18 -# A neat high bun on the back of the crown. -crown_ring = positions[used][np.abs(positions[used, 1]-(eye_height+0.095)) < 0.008] -bun_center = np.array([0.0, eye_height+0.095, crown_ring[:, 2].min()+0.004]) -bun_radii = np.array([0.040, 0.034, 0.038]) -units = np.array([[np.sin(np.pi*ring/rings)*np.cos(2*np.pi*at/segments), np.cos(np.pi*ring/rings), - np.sin(np.pi*ring/rings)*np.sin(2*np.pi*at/segments)] - for ring in range(rings+1) for at in range(segments)]) -bun = bun_center+units*bun_radii -bun_faces = [] -for ring in range(rings): - for at in range(segments): - a, b = ring*segments+at, ring*segments+(at+1) % segments - c, d = a+segments, b+segments - if ring > 0: - bun_faces.append([a, b, d]) - if ring < rings-1: - bun_faces.append([a, d, c]) -bun_faces = outward_faces(bun, bun_faces, bun_center) -extras.append((bun, vertex_normals(bun, bun_faces), np.full(len(bun), 3), bun_faces)) +# A soft hairline: the first few millimetres of hair fade into the skin. +hair_edge = np.clip(1-depth/0.007, 0, 1)**1.5 +bun_center = None +if spec['hair'] == 'bun': + # A neat high bun on the back of the crown. + rings, segments = 14, 24 + crown_ring = shell[np.abs(shell[:, 1]-(eye_height+0.100)) < 0.008] + bun_center = np.array([0.0, eye_height+0.100, crown_ring[:, 2].min()+0.006]) + bun_radii = np.array([0.043, 0.037, 0.041]) + units = np.array([[np.sin(np.pi*ring/rings)*np.cos(2*np.pi*at/segments), np.cos(np.pi*ring/rings), + np.sin(np.pi*ring/rings)*np.sin(2*np.pi*at/segments)] + for ring in range(rings+1) for at in range(segments)]) + bun = bun_center+units*bun_radii + bun_faces = [] + for ring in range(rings): + for at in range(segments): + a, b = ring*segments+at, ring*segments+(at+1) % segments + c, d = a+segments, b+segments + if ring > 0: + bun_faces.append([a, b, d]) + if ring < rings-1: + bun_faces.append([a, d, c]) + bun_faces = outward_faces(bun, bun_faces, bun_center) + extras.append((bun, vertex_normals(bun, bun_faces), np.full(len(bun), 3), bun_faces)) for prefix in ('l', 'r'): indices = sorted({index for face in groups[f'helper-{prefix}-eye'] for index in face}) eye_lookup = {old: at for at, old in enumerate(indices)} @@ -541,8 +692,6 @@ for prefix in ('l', 'r'): eye_faces = outward_faces(eye, [[eye_lookup[face[0]], eye_lookup[face[at]], eye_lookup[face[at+1]]] for face in groups[f'helper-{prefix}-eye'] for at in range(1, len(face)-1)], center) extras.append((eye, vertex_normals(eye, eye_faces), np.zeros(len(eye)), eye_faces)) -head_index = [at for at, item in enumerate(bones) if item['role'] == 3][0] -body_count = len(positions) crown = positions[:, 1].max() for vertices, vertex_normal, vertex_region, faces_of in extras: base = len(positions) @@ -552,69 +701,43 @@ for vertices, vertex_normal, vertex_region, faces_of in extras: weights = np.vstack([weights, np.tile(np.array([1.0, 0.0, 0.0, 0.0]), (len(vertices), 1))]) regions = np.concatenate([regions, np.asarray(vertex_region, dtype=np.uint8)]) triangles = np.vstack([triangles, np.asarray(faces_of, dtype=np.int64)+base]) +head_count = len(positions) +softs = np.zeros(len(positions)) +softs[body_count:body_count+len(hair_edge)] = hair_edge + +# The clothes: shells over the body, skinned by the same rig. +# Regions: 0 skin, 1 top, 2 trousers, 3 hair, 4 trim (the placket's frog knots). -# Her Tai Chi silk suit: shells over the body, skinned by the same rig. The -# mandarin top is fitted over the chest and falls straight from the bust and -# shoulder blades to below the hips, slit at the sides, with a stand-up -# collar and a placket of frog-knot buttons; the long sleeves and the -# trousers fall a little wider towards the wrist and ankle. -# Regions: 0 skin, 1 top, 2 trousers, 3 hair, 4 trim (the placket's frog buttons). -role_of = np.array([item['role'] for item in bones]) def share(rows, shares, roles): return np.sum(shares*np.isin(role_of[rows], roles), axis=1) -def smooth(value): - value = np.clip(value, 0, 1) - return value*value*(3-2*value) arm = share(joints, weights, [4, 5, 6, 7]) trunk_points = (np.arange(len(positions)) < body_count) & (arm < 0.15) -hips_joint = (joint('l-upper-leg')+joint('r-upper-leg'))/2 armpit_y = (joint('l-shoulder')[1]+joint('r-shoulder')[1])/2-0.09 hem_y = hips_joint[1]-0.05 + def slab(height, mask=trunk_points, half=0.012): return positions[mask & (np.abs(positions[:, 1]-height) < half)] + heights = np.arange(hip_height+0.02, joint('spine-1')[1], 0.005) waist_y = heights[int(np.argmin([np.ptp(slab(h, half=0.006)[:, 0]) for h in heights]))] grid_y = np.arange(hem_y-0.04, neck_height+0.0001, 0.01) centre_z = np.array([(lambda s: (s[:, 2].min()+s[:, 2].max())/2)(slab(h)) for h in grid_y]) centre_z = np.convolve(np.pad(centre_z, 2, mode='edge'), np.ones(5)/5, mode='valid') + def trunk_z(y): return np.interp(y, grid_y, centre_z) + K = 72 angles = np.arange(K)*2*np.pi/K directions = np.column_stack((np.sin(angles), np.cos(angles))) -hang = np.zeros((len(grid_y), K)) -for j, h in enumerate(grid_y): - s = slab(h) - hang[j] = (np.column_stack((s[:, 0], s[:, 2]-trunk_z(h))) @ directions.T).max(axis=0) -# Cloth falls straight from the widest place above it, under the armpits. -top = int(np.searchsorted(grid_y, armpit_y)) -for j in range(top-1, -1, -1): - hang[j] = np.maximum(hang[j], hang[j+1]) -# Soft cloth settles part of the way back onto her below the widest place. -hang = 0.65*hang+0.35*np.array([(np.column_stack((s[:, 0], s[:, 2]-trunk_z(h))) @ directions.T).max(axis=0) - for h, s in ((h, slab(h)) for h in grid_y)]) -for _ in range(3): - hang = 0.5*hang+0.25*np.roll(hang, 1, axis=1)+0.25*np.roll(hang, -1, axis=1) -hang[1:-1] = 0.5*hang[1:-1]+0.25*hang[:-2]+0.25*hang[2:] -def hanging_radius(theta, y): - fj = np.clip((y-grid_y[0])/0.01, 0, len(grid_y)-1.001) - j = fj.astype(int) - tj = fj-j - fk = (theta % (2*np.pi))/(2*np.pi)*K - k = np.floor(fk).astype(int) % K - tk = fk-np.floor(fk) - k1 = (k+1) % K - a = hang[j, k]*(1-tk)+hang[j, k1]*tk - b = hang[j+1, k]*(1-tk)+hang[j+1, k1]*tk - return a*(1-tj)+b*tj def arm_progress(points): result = np.zeros(len(points)) @@ -630,10 +753,12 @@ def arm_progress(points): result[mine] = np.where(da < db, a*upper, upper+b*lower)/(upper+lower) return result + dense_body = np.zeros((body_count, len(bones))) for slot in range(4): np.add.at(dense_body, (np.arange(body_count), joints[:body_count, slot]), weights[:body_count, slot]) + def nearest_weights(points, near=8, low=None, high=None): """Skin weights for cloth away from the surface: the weights of the nearest trunk and leg vertices between LOW and HIGH, closer ones counting @@ -650,12 +775,14 @@ def nearest_weights(points, near=8, low=None, high=None): result[at] = share_of @ dense_body[candidates[order]]/share_of.sum() return result -def strongest(dense): + +def strongest_of(dense): rows = np.argsort(-dense, axis=1)[:, :4] shares = np.take_along_axis(dense, rows, axis=1) shares[shares < 0.004] = 0.0 return rows.astype(np.uint8), shares/shares.sum(axis=1)[:, None] + def grid_faces(rows, columns, wrap): faces = [] span = columns if wrap else columns-1 @@ -665,6 +792,7 @@ def grid_faces(rows, columns, wrap): faces += [[a, b, b+columns], [a, b+columns, a+columns]] return np.array(faces, dtype=np.int64) + def facing_out(points, faces, centre_of): normal = np.cross(points[faces[:, 1]]-points[faces[:, 0]], points[faces[:, 2]]-points[faces[:, 0]]) middle = points[faces].mean(axis=1) @@ -673,112 +801,195 @@ def facing_out(points, faces, centre_of): faces[flip] = faces[flip][:, ::-1] return faces + def trunk_axis(points): return np.column_stack((np.zeros(len(points)), points[:, 1], trunk_z(points[:, 1]))) + +def body_shell(faces_of, lift, steps): + """The body's own triangles FACES_OF, lifted by LIFT (one per vertex of + the body) and relaxed like cloth; returns the shell and its vertices.""" + used = np.unique(faces_of) + remap = np.full(len(positions), -1, dtype=np.int64) + remap[used] = np.arange(len(used)) + shell_faces = remap[faces_of] + # Lifted along smoothed normals, so sharp creases (the crotch, the + # armpits) do not fan the cloth out into thin folds that tear in a pose. + edge, count = neighbours(shell_faces, len(used)) + direction = normals[used].copy() + for _ in range(8): + total = np.zeros_like(direction) + np.add.at(total, edge[:, 0], direction[edge[:, 1]]) + direction = 0.5*direction+0.5*total/count[:, None] + direction /= np.maximum(np.linalg.norm(direction, axis=1)[:, None], 1e-12) + q = relax(positions[used], direction, lift[used], shell_faces, steps) + return used, q, shell_faces + + cloth = [] # (points, normals, joints, weights, region, faces, source positions or None, hang, UVs or None) +body_faces = np.all(triangles < body_count, axis=1) +down = np.clip((top_hem-positions[:, 1])/(top_hem-np.mean(ankles)), 0, 1) +if fitted: + trouser_lift = 0.005+0.012*smooth(down) + # The fitted top: the body's own surface lifted a little and smoothed + # the way silk lies, over the chest, the waist and the hips to just + # below the hip bones, and down a third of each upper arm. Its hem laps + # over the trousers' waist. + lap = body_faces & np.all(regions[triangles] == 2, axis=1) & np.all(positions[triangles][:, :, 1] > top_hem-0.025, axis=1) + top_faces = triangles[(body_faces & np.all(regions[triangles] == 1, axis=1)) | lap] + lift = np.full(len(positions), 0.0035) + lift[positions[:, 1] < top_hem+0.002] = trouser_lift[positions[:, 1] < top_hem+0.002]+0.0025 + used, q, faces_of = body_shell(top_faces, lift, 14) + top_shell = q + cloth.append((q, vertex_normals(q, faces_of), joints[used], weights[used], 1, faces_of, positions[used], + np.zeros(len(q)), None)) + placket_low = (waist_y+armpit_y)/2-0.02 +else: + hang = np.zeros((len(grid_y), K)) + for j, h in enumerate(grid_y): + s = slab(h) + hang[j] = (np.column_stack((s[:, 0], s[:, 2]-trunk_z(h))) @ directions.T).max(axis=0) + # Cloth falls straight from the widest place above it, under the armpits. + top_row = int(np.searchsorted(grid_y, armpit_y)) + for j in range(top_row-1, -1, -1): + hang[j] = np.maximum(hang[j], hang[j+1]) + # Soft cloth settles part of the way back onto him below the widest place. + hang = 0.65*hang+0.35*np.array([(np.column_stack((s[:, 0], s[:, 2]-trunk_z(h))) @ directions.T).max(axis=0) + for h, s in ((h, slab(h)) for h in grid_y)]) + for _ in range(3): + hang = 0.5*hang+0.25*np.roll(hang, 1, axis=1)+0.25*np.roll(hang, -1, axis=1) + hang[1:-1] = 0.5*hang[1:-1]+0.25*hang[:-2]+0.25*hang[2:] -# The mandarin top: the body's own surface lifted a little off it, fitted -# over the chest and along the long sleeves. -top_faces = triangles[np.all(regions[triangles] == 1, axis=1) & np.all(triangles < body_count, axis=1)] -top_faces = top_faces[(positions[top_faces][:, :, 1].min(axis=1) > waist_y-0.03) | (arm[top_faces].mean(axis=1) > 0.5)] -used = np.unique(top_faces) -p, n = positions[used], normals[used] -bust_y = slab((waist_y+armpit_y)/2, half=0.06)[:, 1][np.argmax(slab((waist_y+armpit_y)/2, half=0.06)[:, 2])] -sleeve = smooth((arm[used]-0.2)/0.6) -lift = np.interp(p[:, 1], [waist_y, bust_y, neck_height-0.04], [0.010, 0.007, 0.004])*(1-sleeve) -lift += (0.006+0.014*arm_progress(p)**1.5)*sleeve -q = p+n*lift[:, None] -rel = np.column_stack((q[:, 0], q[:, 2]-trunk_z(p[:, 1]))) -theta = np.arctan2(rel[:, 0], rel[:, 1]) -push = np.maximum(hanging_radius(theta, p[:, 1])+lift-np.linalg.norm(rel, axis=1), 0) -push *= (1-sleeve)*np.clip((armpit_y-p[:, 1])/0.06, 0, 1) -q[:, 0] += np.sin(theta)*push -q[:, 2] += np.cos(theta)*push -remap = np.full(len(positions), -1, dtype=np.int64) -remap[used] = np.arange(len(used)) -faces_of = remap[top_faces] -top_shell = q -cloth.append((q, vertex_normals(q, faces_of), joints[used], weights[used], 1, faces_of, p, np.zeros(len(q)), None)) + def hanging_radius(theta, y): + fj = np.clip((y-grid_y[0])/0.01, 0, len(grid_y)-1.001) + j = fj.astype(int) + tj = fj-j + fk = (theta % (2*np.pi))/(2*np.pi)*K + k = np.floor(fk).astype(int) % K + tk = fk-np.floor(fk) + k1 = (k+1) % K + a = hang[j, k]*(1-tk)+hang[j, k1]*tk + b = hang[j+1, k]*(1-tk)+hang[j+1, k1]*tk + return a*(1-tj)+b*tj -# The top's hip-length lower part, from just above the waist to below the -# hip bones, slit at both sides. -rows_y = np.linspace(waist_y+0.035, hem_y, 12) -fall = (rows_y[0]-rows_y)/(rows_y[0]-rows_y[-1]) -skirt = [] -for y, f in zip(rows_y, fall): - r = hanging_radius(angles, np.full(K, y))+0.010+0.012*f**1.5 - skirt.append(np.column_stack((np.sin(angles)*r, np.full(K, y), trunk_z(y)+np.cos(angles)*r))) -skirt = np.vstack(skirt) -faces_of = grid_faces(len(rows_y), K, True) -side = np.abs(np.sin(angles[faces_of[:, 0] % K]+np.pi/K)) > 0.97 -faces_of = facing_out(skirt, faces_of[~(side & (faces_of[:, 0]//K >= len(rows_y)//2))], trunk_axis) -dense = nearest_weights(skirt).reshape(len(rows_y), K, len(bones)) -for _ in range(2): - dense = 0.5*dense+0.25*np.roll(dense, 1, axis=1)+0.25*np.roll(dense, -1, axis=1) -# The hand-over from the pelvis to the thighs spreads down the whole hem, -# so a lifted leg draws it out gradually instead of tearing a band. -for _ in range(12): - dense[1:-1] = 0.5*dense[1:-1]+0.25*dense[:-2]+0.25*dense[2:] - dense[-1] = 0.5*dense[-1]+0.5*dense[-2] -rows, shares = strongest(dense.reshape(-1, len(bones))) -cloth.append((skirt, vertex_normals(skirt, faces_of), rows, shares, 1, faces_of, None, np.repeat(fall, K), None)) + # The jacket: the body's own surface lifted off it over the chest and + # along the long sleeves, falling wider towards the wrist. + top_faces = triangles[body_faces & np.all(regions[triangles] == 1, axis=1)] + top_faces = top_faces[(positions[top_faces][:, :, 1].min(axis=1) > waist_y-0.03) | (arm[top_faces].mean(axis=1) > 0.5)] + used = np.unique(top_faces) + p, n = positions[used], normals[used] + bust_y = slab((waist_y+armpit_y)/2, half=0.06)[:, 1][np.argmax(slab((waist_y+armpit_y)/2, half=0.06)[:, 2])] + sleeve = smooth((arm[used]-0.2)/0.6) + lift = np.interp(p[:, 1], [waist_y, bust_y, neck_height-0.04], [0.010, 0.007, 0.005])*(1-sleeve) + lift += (0.007+0.016*arm_progress(p)**1.5)*sleeve + q = p+n*lift[:, None] + rel = np.column_stack((q[:, 0], q[:, 2]-trunk_z(p[:, 1]))) + theta = np.arctan2(rel[:, 0], rel[:, 1]) + push = np.maximum(hanging_radius(theta, p[:, 1])+lift-np.linalg.norm(rel, axis=1), 0) + push *= (1-sleeve)*np.clip((armpit_y-p[:, 1])/0.06, 0, 1) + q[:, 0] += np.sin(theta)*push + q[:, 2] += np.cos(theta)*push + remap = np.full(len(positions), -1, dtype=np.int64) + remap[used] = np.arange(len(used)) + faces_of = remap[top_faces] + # Loose cloth hides the muscles under it: smooth the jacket, never + # letting it sink back towards him. + q = relax(q, vertex_normals(q, faces_of), np.zeros(len(q)), faces_of, 30) + top_shell = q + cloth.append((q, vertex_normals(q, faces_of), joints[used], weights[used], 1, faces_of, p, np.zeros(len(q)), None)) -# The stand-up mandarin collar round the base of her neck, leaning in a + # The jacket's skirt, from just above the waist to below the hip bones, + # slit at both sides for its lower third. + rows_y = np.linspace(waist_y+0.035, hem_y, 12) + fall = (rows_y[0]-rows_y)/(rows_y[0]-rows_y[-1]) + skirt = [] + for y, f in zip(rows_y, fall): + r = hanging_radius(angles, np.full(K, y))+0.010+0.012*f**1.5 + skirt.append(np.column_stack((np.sin(angles)*r, np.full(K, y), trunk_z(y)+np.cos(angles)*r))) + skirt = np.vstack(skirt) + faces_of = grid_faces(len(rows_y), K, True) + side_of = np.abs(np.sin(angles[faces_of[:, 0] % K]+np.pi/K)) > 0.97 + faces_of = facing_out(skirt, faces_of[~(side_of & (faces_of[:, 0]//K >= 2*len(rows_y)//3))], trunk_axis) + dense = nearest_weights(skirt).reshape(len(rows_y), K, len(bones)) + for _ in range(2): + dense = 0.5*dense+0.25*np.roll(dense, 1, axis=1)+0.25*np.roll(dense, -1, axis=1) + # The hand-over from the pelvis to the thighs spreads down the whole hem, + # so a lifted leg draws it out gradually instead of tearing a band. + for _ in range(12): + dense[1:-1] = 0.5*dense[1:-1]+0.25*dense[:-2]+0.25*dense[2:] + dense[-1] = 0.5*dense[-1]+0.5*dense[-2] + rows, shares = strongest_of(dense.reshape(-1, len(bones))) + cloth.append((skirt, vertex_normals(skirt, faces_of), rows, shares, 1, faces_of, None, np.repeat(fall, K), None)) + placket_low = hem_y+0.004 + +# The stand-up mandarin collar round the base of the neck, leaning in a # little at its top. collar_y = neck_height+np.array([-0.012, 0.006, 0.022]) collar_angles = np.arange(48)*2*np.pi/48 +dip = 0.013*np.maximum(np.cos(collar_angles), 0)**2 collar = [] -for y, give in zip(collar_y, (0.005, 0.004, 0.002)): - s = positions[:body_count][(arm[:body_count] < 0.15) & (np.abs(positions[:body_count, 1]-y) < 0.006)] - middle = (s[:, 2].min()+s[:, 2].max())/2 - reach = (np.column_stack((s[:, 0], s[:, 2]-middle)) @ np.column_stack((np.sin(collar_angles), np.cos(collar_angles))).T).max(axis=0) - collar.append(np.column_stack((np.sin(collar_angles)*(reach+give), np.full(48, y), middle+np.cos(collar_angles)*(reach+give)))) +neck_points = positions[:body_count][arm[:body_count] < 0.15] +for y, give, follow in zip(collar_y, (0.006, 0.004, 0.002), (1.0, 0.6, 0.35)): + ring = [] + for angle, low in zip(collar_angles, dip*follow): + at = y-low + s = neck_points[np.abs(neck_points[:, 1]-at) < 0.006] + middle = (s[:, 2].min()+s[:, 2].max())/2 + reach = (np.column_stack((s[:, 0], s[:, 2]-middle)) @ np.array([np.sin(angle), np.cos(angle)])).max() + ring.append([np.sin(angle)*(reach+give), at, middle+np.cos(angle)*(reach+give)]) + collar.append(np.array(ring)) collar = np.vstack(collar) faces_of = facing_out(collar, grid_faces(3, 48, True), lambda m: np.column_stack((np.zeros(len(m)), m[:, 1], np.full(len(m), collar[:, 2].mean())))) -rows, shares = strongest(nearest_weights(collar, low=neck_height-0.05, high=neck_height+0.05)) +rows, shares = strongest_of(nearest_weights(collar, low=neck_height-0.05, high=neck_height+0.05)) cloth.append((collar, vertex_normals(collar, faces_of), rows, shares, 1, faces_of, None, np.zeros(len(collar)), None)) -# The placket down her front with its frog-knot buttons, just over the top. -front = np.vstack([top_shell[np.abs(top_shell[:, 0]) < 0.01], skirt[np.abs(skirt[:, 0]) < 0.01]]) -front = front[np.argsort(front[:, 1])] -placket_y = np.arange(neck_height-0.012, hem_y+0.004, -0.01) +# The placket down the front with its frog-knot buttons, just over the top: +# to the middle of her chest, all the way down his jacket. +front = top_shell[np.abs(top_shell[:, 0]) < 0.01] +if not fitted: + front = np.vstack([front, skirt[np.abs(skirt[:, 0]) < 0.01]]) +placket_y = np.arange(neck_height-0.012, placket_low, -0.01) reach = np.array([front[np.abs(front[:, 1]-y) < 0.012][:, 2].max() for y in placket_y]) placket = np.vstack([[[side*0.015, y, z+0.0025] for side in (-1, 1)] for y, z in zip(placket_y, reach)]) faces_of = facing_out(placket, grid_faces(len(placket_y), 2, False), trunk_axis) -rows, shares = strongest(nearest_weights(placket, low=hem_y-0.12, high=neck_height+0.02)) -placket_hang = np.repeat(np.clip((rows_y[0]-placket_y)/(rows_y[0]-rows_y[-1]), 0, 1), 2) +rows, shares = strongest_of(nearest_weights(placket, low=placket_low-0.12, high=neck_height+0.02)) +if fitted: + placket_hang = np.zeros(len(placket)) +else: + placket_hang = np.repeat(np.clip((rows_y[0]-placket_y)/(rows_y[0]-rows_y[-1]), 0, 1), 2) placket_uv = np.column_stack((np.tile([0.0, 1.0], len(placket_y)), np.repeat((placket_y[0]-placket_y)/0.045, 2))) cloth.append((placket, vertex_normals(placket, faces_of), rows, shares, 4, faces_of, None, placket_hang, placket_uv)) -# The trousers: the legs' surface lifted off them, falling wide in soft -# silk and gathered again at the ankle. -leg_faces = triangles[np.all(regions[triangles] == 2, axis=1) & np.all(triangles < body_count, axis=1)] -used = np.unique(leg_faces) -p, n = positions[used], normals[used] -down = np.clip((hip_height-0.04-p[:, 1])/(hip_height-0.04-np.mean(ankles)), 0, 1) -lift = 0.012+0.034*smooth(down/0.75)-0.026*smooth((down-0.85)/0.15) -q = p+n*lift[:, None] -remap = np.full(len(positions), -1, dtype=np.int64) -remap[used] = np.arange(len(used)) -faces_of = remap[leg_faces] -cloth.append((q, vertex_normals(q, faces_of), joints[used], weights[used], 2, faces_of, p, np.zeros(len(q)), None)) +# The trousers: the legs' surface lifted off them. Hers are slim and fall +# straight to the ankle; his fall wide and gather again at the ankle. +leg_faces = triangles[body_faces & np.all(regions[triangles] == 2, axis=1)] +if fitted: + used, q, faces_of = body_shell(leg_faces, trouser_lift, 30) +else: + # Smoothed like the rest, so the crotch is bridged rather than lifted + # into thin folds that tear when he folds forward. + lift = 0.010+0.028*smooth(down/0.75)-0.020*smooth((down-0.85)/0.15) + lift *= 0.4+0.6*smooth((np.abs(positions[:, 0])-0.02)/0.05) + used, q, faces_of = body_shell(leg_faces, lift, 30) +cloth.append((q, vertex_normals(q, faces_of), joints[used], weights[used], 2, faces_of, positions[used], + np.zeros(len(q)), None)) -# Painted textures follow the form: the trunk and the head are wrapped -# about the vertical, each arm and leg about its own length, so brush -# strokes run down the body and along the limbs. Each wrap is mirrored at -# its back and front, so it has no seam. +# Texture coordinates follow the form: the trunk and the head are wrapped +# about the vertical, each arm and leg about its own length. CLOTH_TILE = 0.30 HAIR_TILE = 0.18 + def trunk_uv(points): turn = np.abs(np.arctan2(points[:, 0], points[:, 2]-trunk_z(points[:, 1])))/np.pi return np.column_stack((turn*0.45/CLOTH_TILE, points[:, 1]/CLOTH_TILE)) + def head_uv(points): - turn = np.abs(np.arctan2(points[:, 0], points[:, 2]-joint('head')[2]))/np.pi + turn = np.abs(np.arctan2(points[:, 0], points[:, 2]-head_centre_z))/np.pi return np.column_stack((turn*0.28/HAIR_TILE, points[:, 1]/HAIR_TILE)) + def limb_uv(points, start, end, half_round): axis = (end-start)/np.linalg.norm(end-start) forward = np.array([0.0, 0.0, 1.0])-axis*axis[2] @@ -788,6 +999,7 @@ def limb_uv(points, start, end, half_round): turn = np.abs(np.arctan2(rel @ across, rel @ forward))/np.pi return np.column_stack((turn*half_round/CLOTH_TILE, -(rel @ axis)/CLOTH_TILE)) + def wrapped_uv(points, rows, shares): dominant = rows[np.arange(len(rows)), np.argmax(shares, axis=1)] roles = role_of[dominant] @@ -802,67 +1014,240 @@ def wrapped_uv(points, rows, shares): result[limb] = limb_uv(points[limb], joint(prefix+'-upper-leg'), joint(prefix+'-ankle'), 0.25) return result -# Black cloth shoes: below the trouser hems her feet take the sleek black -# of her hair. -shoes = (np.arange(len(positions)) < body_count) & (regions == 0) & (positions[:, 1] <= max(ankles)+1e-6) -regions[shoes] = 3 + uvs = wrapped_uv(positions, joints, weights) hangs = np.zeros(len(positions)) -hair = (regions == 3) & ~shoes -# Hair strokes run from the hairline back into the bun. -swept = positions[hair]-bun_center +# Hair runs from the hairline back to the bun, or from the crown's whorl. +hair = regions == 3 +sweep = bun_center if bun_center is not None else np.array([0.0, eye_height+0.105, head_centre_z-0.045]) +swept = positions[hair]-sweep uvs[hair] = np.column_stack((np.abs(np.arctan2(swept[:, 0], swept[:, 1]))/np.pi*0.25/HAIR_TILE, np.linalg.norm(swept, axis=1)/HAIR_TILE)) -for points, vertex_normal, rows, shares, region, faces_of, source, hanging, given_uv in cloth: +for points_of, vertex_normal, rows, shares, region, faces_of, source_of, hanging, given_uv in cloth: base = len(positions) if given_uv is not None: uv = given_uv - elif source is None: - uv = trunk_uv(points) + elif source_of is None: + uv = trunk_uv(points_of) else: - uv = wrapped_uv(source, rows, shares) - positions = np.vstack([positions, points]) + uv = wrapped_uv(source_of, rows, shares) + positions = np.vstack([positions, points_of]) normals = np.vstack([normals, vertex_normal]) joints = np.vstack([joints, np.asarray(rows, dtype=np.uint8)]) weights = np.vstack([weights, shares]) - regions = np.concatenate([regions, np.full(len(points), region, dtype=np.uint8)]) + regions = np.concatenate([regions, np.full(len(points_of), region, dtype=np.uint8)]) triangles = np.vstack([triangles, faces_of+base]) uvs = np.vstack([uvs, uv]) hangs = np.concatenate([hangs, hanging]) + softs = np.concatenate([softs, np.zeros(len(points_of))]) -# The face is painted by face.webp, projected from the front onto the -# head: its eyes, mouth and the mesh's own match exactly, and the painting -# fades out towards the ears, the hairline and under the chin. -FACE = dict(size=(1254, 1254), right_eye=(480, 520), left_eye=(770, 520), mouth=(628, 782)) -face_ready = FACE['right_eye'] != (0, 0) -mouth_point = np.array([0.0, joint('mouth')[1]-0.027]) -mesh_marks = np.array([joint('r-eye')[:2], joint('l-eye')[:2], mouth_point]) -picture = np.array([FACE['right_eye'], FACE['left_eye'], FACE['mouth']], dtype=np.float64) -picture = np.column_stack((picture[:, 0]/FACE['size'][0], 1-picture[:, 1]/FACE['size'][1])) -mapping = np.linalg.solve(np.column_stack((mesh_marks, np.ones(3))), picture) -details = np.column_stack((positions[:, :2], np.ones(len(positions)))) @ mapping +# The face is drawn in face.webp, which lies on the head as seen from the +# front: FACE_SIZE metres square about the middle of the face. Its features +# are drawn on the mesh's own: the lids' lash lines, the eyeballs and the +# mouth between the teeth. +FACE_SIZE = 0.22 +face_low = np.array([-FACE_SIZE/2, eye_height-0.14]) +details = (positions[:, :2]-face_low)/FACE_SIZE x, y = positions[:, 0], positions[:, 1] -oval = ((x/0.078)**2+((y-eye_height+0.02)/0.100)**2)**0.5 -mask = smooth((normals[:, 2]-0.12)/0.4)*smooth((1.0-oval)/0.25)*smooth(-hairline(positions)/0.012) -mask *= (role_of[joints[:, 0]] == 3) & (regions == 0) & face_ready +oval = ((x/0.080)**2+((y-eye_height+0.02)/0.105)**2)**0.5 +mask = smooth((normals[:, 2]-0.10)/0.4)*smooth((1.0-oval)/0.25)*smooth(-hairline(positions)/0.006) +mask *= (role_of[joints[:, 0]] == 3) & (regions == 0) details[mask <= 0] = 0.0 # Cloth's detail is how freely it hangs from the waist: 0 at the waist, 1 -# at the top's hem. +# at the jacket's hem; the hair's is how far it fades into the skin. details[regions != 0] = np.column_stack((hangs, np.zeros(len(hangs))))[regions != 0] +details[regions == 3] = np.column_stack((softs, np.zeros(len(softs))))[regions == 3] masks = np.rint(np.clip(mask, 0, 1)*255).astype(np.int64) -# The body under the top and the trousers never shows: drop it, keeping -# the skin near the cuffs, the collar and the trouser hems, where it can be -# seen inside. Fewer triangles to skin, upload and draw every frame. + +def draw_face(path): + """Draws the face as a clean, flat colour map over the skin colour.""" + from PIL import Image, ImageDraw, ImageFilter + size, over = 1024, 2 + canvas = size*over + skin = colour(spec['colours']['skin']) + + def pixel(point): + return ((point[0]-face_low[0])/FACE_SIZE*canvas, (1-(point[1]-face_low[1])/FACE_SIZE)*canvas) + + def metres(value): + return value/FACE_SIZE*canvas + + layers = [] + + def layer(fill, alpha, draw_with, blur=0.0): + mask_image = Image.new('L', (canvas, canvas), 0) + draw_with(ImageDraw.Draw(mask_image)) + if blur: + mask_image = mask_image.filter(ImageFilter.GaussianBlur(metres(blur))) + layers.append((colour(fill) if isinstance(fill, str) else fill, alpha, np.asarray(mask_image, dtype=np.float64)/255)) + + def stroke(points, widths): + def draw_with(draw): + for at in range(len(points)-1): + a, b = pixel(points[at]), pixel(points[at+1]) + w = metres((widths[at]+widths[at+1])/2) + draw.line([a, b], fill=255, width=max(1, int(round(w)))) + draw.ellipse([b[0]-w/2, b[1]-w/2, b[0]+w/2, b[1]+w/2], fill=255) + return draw_with + + female = spec['gender'] == 'female' + for prefix, sign in (('l', 1.0), ('r', -1.0)): + eye = helper_points(f'helper-{prefix}-eye') + centre = eye.mean(axis=0) + margins = [] + for strip in (f'helper-{prefix}-eyelashes-2', f'helper-{prefix}-eyelashes-1'): + lashes = helper_points(strip) + root = lashes[np.argsort(np.linalg.norm(lashes-centre, axis=1))[:len(lashes)//2]] + # The lid's edge: a smooth curve through the lash roots. + across = np.linspace(root[:, 0].min(), root[:, 0].max(), 24) + line = np.column_stack([across]+[np.polyval(np.polyfit(root[:, 0], root[:, axis], 3), across) + for axis in (1, 2)]) + margins.append(line if sign > 0 else line[::-1]) + upper, lower = margins + # The opening between the lids, closed at both corners. + inner = min(upper[:, 0].min(), lower[:, 0].min()) if sign > 0 else max(upper[:, 0].max(), lower[:, 0].max()) + outline = list(upper)+list(lower[::-1]) + opening = [pixel(point) for point in outline] + layer('#f6f1ec', 1.0, lambda draw: draw.polygon(opening, fill=255), 0.0002) + iris_centre = np.array([centre[0]+sign*0.0004, (upper[:, 1].max()+lower[:, 1].min())/2+0.0006]) + iris = 0.0056 if female else 0.0052 + + def disc(point, radius): + c = pixel(point) + r = metres(radius) + return lambda draw: draw.ellipse([c[0]-r, c[1]-r, c[0]+r, c[1]+r], fill=255) + + clip = Image.new('L', (canvas, canvas), 0) + ImageDraw.Draw(clip).polygon(opening, fill=255) + clip = np.asarray(clip.filter(ImageFilter.GaussianBlur(metres(0.0002))), dtype=np.float64)/255 + for fill, radius, alpha in ((spec['colours']['iris'], iris, 1.0), ('#5c3a27', iris*0.72, 0.55), + ('#0c0908', 0.0024, 1.0)): + start = len(layers) + layer(fill, alpha, disc(iris_centre, radius), 0.0002) + fill_of, alpha_of, mask_of = layers[start] + layers[start] = (fill_of, alpha_of, mask_of*clip) + for offset, radius in (((-0.0016*sign, 0.0018), 0.0009), ((0.0017*sign, -0.0014), 0.00045)): + start = len(layers) + layer('#ffffff', 0.9, disc(iris_centre+np.array(offset), radius), 0.0001) + fill_of, alpha_of, mask_of = layers[start] + layers[start] = (fill_of, alpha_of, mask_of*clip) + # Lash lines: the upper thick and dark, flicking up a little past the + # outer corner; the lower soft. + span = np.abs(upper[:, 0]-inner)/max(np.ptp(upper[:, 0]), 1e-6) + thick = (0.0008+0.0007*span) if female else (0.0006+0.0003*span) + line = list(upper) + if female: + outer = upper[np.argmax(np.abs(upper[:, 0]-inner))] + line.append(outer+np.array([sign*0.0028, 0.0013, 0.0])) + thick = np.append(thick, 0.0004) + layer(spec['colours']['lashes'], 1.0, stroke(line, thick), 0.00012) + lower_span = np.abs(lower[:, 0]-inner)/max(np.ptp(lower[:, 0]), 1e-6) + layer('#6b4a3e', 0.55, stroke(list(lower), 0.00025+0.0002*lower_span), 0.00015) + # A soft fold over the upper lid. + crease = upper[1:-1]+np.array([0.0, 0.0024, 0.0]) + layer('#b98c7a', 0.35 if female else 0.25, stroke(list(crease), np.full(len(crease), 0.0003)), 0.0003) + # The brow. + top = upper[:, 1].max() + brow = np.array([[inner-sign*0.0025, top+0.0080], [centre[0]+sign*0.002, top+0.0108], + [centre[0]+sign*0.0115, top+0.0108], [centre[0]+sign*0.0185, top+0.0070]]) + brow = np.array([np.interp(t, [0, 1, 2, 3], brow[:, 0]) for t in np.linspace(0, 3, 16)]), \ + np.array([np.interp(t, [0, 1, 2, 3], brow[:, 1]) for t in np.linspace(0, 3, 16)]) + brow = np.column_stack(brow) + widths = np.linspace(0.0021, 0.0008, len(brow)) if female else np.linspace(0.0034, 0.0020, len(brow)) + layer(spec['colours']['brows'], 0.85 if female else 0.92, stroke(list(brow), widths), 0.0005) + if female and spec['colours']['blush']: + cheek = pixel(np.array([centre[0]+sign*0.006, centre[1]-0.026])) + rx, ry = metres(0.016), metres(0.010) + layer(spec['colours']['blush'], 0.30, + lambda draw: draw.ellipse([cheek[0]-rx, cheek[1]-ry, cheek[0]+rx, cheek[1]+ry], fill=255), 0.006) + # The lips, on the line where the teeth meet. + upper_teeth, lower_teeth = helper_points('helper-upper-teeth'), helper_points('helper-lower-teeth') + mouth = (upper_teeth[:, 1].min()+lower_teeth[:, 1].max())/2+0.001 + half = 0.0205 if female else 0.0235 + + def lips(draw): + upper_lip = [(-half, 0.0), (-half*0.55, 0.0032), (-0.0035, 0.0052), (0.0, 0.0040), (0.0035, 0.0052), + (half*0.55, 0.0032), (half, 0.0)] + lower_lip = [(half, 0.0), (half*0.55, -0.0050), (0.0, -0.0066), (-half*0.55, -0.0050)] + draw.polygon([pixel(np.array([x, mouth+y])) for x, y in upper_lip+lower_lip], fill=255) + + layer(spec['colours']['lips'], 0.85 if female else 0.45, lips, 0.0005) + layer('#9c4b56' if female else '#8f5c55', 0.6, + stroke([np.array([x, mouth+0.0006*(1-(x/half)**2)]) for x in np.linspace(-half*0.95, half*0.95, 15)], + np.full(15, 0.0005)), 0.0002) + if female: + shine = pixel(np.array([0.003, mouth-0.0035])) + rx, ry = metres(0.0045), metres(0.0012) + layer('#ffffff', 0.25, lambda draw: draw.ellipse([shine[0]-rx, shine[1]-ry, shine[0]+rx, shine[1]+ry], + fill=255), 0.0008) + picture = np.tile(skin, (canvas, canvas, 1)) + for fill, alpha, mask_of in layers: + weight = (mask_of*alpha)[:, :, None] + picture = picture*(1-weight)+fill*weight + image = Image.fromarray(np.clip(picture, 0, 255).astype(np.uint8)).resize((size, size), Image.LANCZOS) + image.save(path, quality=92, method=6) + + +def draw_trim(path): + """The placket: a strip of the top's colour edged with fine piping, one + frog knot to each repeat.""" + from PIL import Image, ImageDraw, ImageFilter + size = 512 + background = colour(spec['colours']['top'])*0.92 + knot = colour(spec['colours']['knot']) + mask_image = Image.new('L', (size, size), 0) + draw = ImageDraw.Draw(mask_image) + draw.rounded_rectangle([size*0.10, size*0.44, size*0.90, size*0.56], radius=size*0.06, fill=255) + for at in (0.30, 0.70): + draw.ellipse([size*(at-0.10), size*0.38, size*(at+0.10), size*0.62], outline=255, width=int(size*0.045)) + draw.ellipse([size*0.41, size*0.41, size*0.59, size*0.59], fill=255) + draw.line([(size*0.04, 0), (size*0.04, size)], fill=255, width=int(size*0.025)) + draw.line([(size*0.96, 0), (size*0.96, size)], fill=255, width=int(size*0.025)) + weight = np.asarray(mask_image.filter(ImageFilter.GaussianBlur(1.2)), dtype=np.float64)[:, :, None]/255 + picture = background*(1-weight)+knot*weight + Image.fromarray(np.clip(picture, 0, 255).astype(np.uint8)).resize((256, 256), Image.LANCZOS).save( + path, quality=92, method=6) + + +def draw_hair(path): + """Hair: its colour with soft, faint lighter and darker strands along + the texture's height.""" + from PIL import Image + size = 256 + across = np.arange(size)/size + random = np.random.default_rng(7) + shade = np.zeros(size) + for cycles, amount in ((5, 0.05), (11, 0.04), (19, 0.03), (31, 0.025), (47, 0.02)): + shade += amount*np.sin(2*np.pi*(cycles*across+random.random())) + picture = colour(spec['colours']['hair'])[None, None, :]*(1+shade)[None, :, None] + Image.fromarray(np.clip(np.repeat(picture, size, axis=0), 0, 255).astype(np.uint8)).save(path, lossless=True) + + +def draw_plain(path, text): + from PIL import Image + Image.fromarray(np.tile(colour(text), (32, 32, 1)).astype(np.uint8)).save(path, lossless=True) + + +# The body under the clothes never shows: drop it, keeping the skin near +# the cuffs, the collar and the hems, where it can be seen inside. Fewer +# triangles to skin, upload and draw every frame. corners = positions[triangles] body_face = np.all(triangles < body_count, axis=1) -progress = arm_progress(corners.reshape(-1, 3)).reshape(-1, 3).max(axis=1) face_arm = share(joints, weights, [4, 5, 6, 7])[triangles].mean(axis=1) -leg_down = np.clip((hip_height-0.04-corners[:, :, 1].min(axis=1))/(hip_height-0.04-np.mean(ankles)), 0, 1) -hidden_top = (regions[triangles[:, 0]] == 1) & ((face_arm < 0.5) | (progress < 0.8)) & \ - (corners[:, :, 1].max(axis=1) < neck_height-0.05) & ((face_arm >= 0.5) | (corners[:, :, 1].min(axis=1) > waist_y)) +leg_down = np.clip((top_hem-corners[:, :, 1].min(axis=1))/(top_hem-np.mean(ankles)), 0, 1) hidden_legs = (regions[triangles[:, 0]] == 2) & (leg_down < 0.8) -triangles = triangles[~(body_face & (hidden_top | hidden_legs))] +if fitted: + near_sleeve = sleeve_end(corners.reshape(-1, 3)).reshape(-1, 3).max(axis=1) > -0.03 + hidden_top = (regions[triangles[:, 0]] == 1) & ~near_sleeve & \ + (corners[:, :, 1].max(axis=1) < neck_height-0.05) & (corners[:, :, 1].min(axis=1) > top_hem+0.03) +else: + progress = arm_progress(corners.reshape(-1, 3)).reshape(-1, 3).max(axis=1) + hidden_top = (regions[triangles[:, 0]] == 1) & ((face_arm < 0.5) | (progress < 0.8)) & \ + (corners[:, :, 1].max(axis=1) < neck_height-0.05) & ((face_arm >= 0.5) | (corners[:, :, 1].min(axis=1) > waist_y)) +# The scalp lies under the hair shell, which starts on it at the hairline. +hidden_scalp = np.all(regions[triangles] == 3, axis=1) +triangles = triangles[~(body_face & (hidden_top | hidden_legs | hidden_scalp))] kept = np.unique(triangles) renumber = np.full(len(positions), -1, dtype=np.int64) renumber[kept] = np.arange(len(kept)) @@ -886,16 +1271,24 @@ for point, normal, uv, detail, influence, weight, region, face in zip(positions, blob.extend(struct.pack('<3f3h2f2f4B4HBB', *point, *np.rint(normal*32767).astype(int), *uv, *detail, *influence, *weight, int(region), int(face))) blob.extend(triangles.astype('