FruityDance.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. #include "core/FruityDance.h"
  2. #include <algorithm>
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <cstring>
  6. #include <sstream>
  7. #include "core/Instruments.h"
  8. namespace lynx::dance
  9. {
  10. namespace
  11. {
  12. constexpr float twoPi = 6.28318530718f;
  13. const char* moveIds[] = { "freestyle", "waiting", "stepping", "jumping", "zombie", "waving", "hula", "windmill", "flail", "spin", "held" };
  14. std::uint32_t mixBits (std::uint32_t x) noexcept
  15. {
  16. x ^= x >> 16;
  17. x *= 0x7feb352du;
  18. x ^= x >> 15;
  19. x *= 0x846ca68bu;
  20. x ^= x >> 16;
  21. return x;
  22. }
  23. float smooth (float t) noexcept { return t * t * (3.0f - 2.0f * t); }
  24. bool validUtf8 (const std::string& s) noexcept
  25. {
  26. for (std::size_t i = 0; i < s.size();)
  27. {
  28. const auto c = (unsigned char) s[i];
  29. const auto extra = c < 0x80 ? 0 : (c >> 5) == 0x6 ? 1 : (c >> 4) == 0xe ? 2 : (c >> 3) == 0x1e ? 3 : -1;
  30. if (extra < 0 || i + (std::size_t) extra >= s.size())
  31. return false;
  32. for (int k = 1; k <= extra; ++k)
  33. if (((unsigned char) s[i + (std::size_t) k] >> 6) != 0x2)
  34. return false;
  35. i += (std::size_t) extra + 1;
  36. }
  37. return true;
  38. }
  39. // text that is not UTF-8 is read as Latin-1
  40. std::string toUtf8 (const std::string& s)
  41. {
  42. if (validUtf8 (s))
  43. return s;
  44. std::string out;
  45. for (const auto ch : s)
  46. {
  47. const auto c = (unsigned char) ch;
  48. if (c < 0x80)
  49. out += (char) c;
  50. else
  51. {
  52. out += (char) (0xc0 | (c >> 6));
  53. out += (char) (0x80 | (c & 0x3f));
  54. }
  55. }
  56. return out;
  57. }
  58. // FL's text is UTF-8: a byte that is not part of a valid UTF-8 character becomes U+FFFD (the result is always UTF-8)
  59. std::string validUtf8OnlyText (const std::string& s)
  60. {
  61. if (validUtf8 (s))
  62. return s;
  63. std::string out;
  64. for (std::size_t i = 0; i < s.size();)
  65. {
  66. const auto c = (unsigned char) s[i];
  67. const auto extra = c < 0x80 ? 0 : (c >> 5) == 0x6 ? 1 : (c >> 4) == 0xe ? 2 : (c >> 3) == 0x1e ? 3 : -1;
  68. bool ok = extra >= 0 && i + (std::size_t) extra < s.size();
  69. for (int k = 1; ok && k <= extra; ++k)
  70. ok = ((unsigned char) s[i + (std::size_t) k] >> 6) == 0x2;
  71. if (ok)
  72. {
  73. out.append (s, i, (std::size_t) extra + 1);
  74. i += (std::size_t) extra + 1;
  75. }
  76. else
  77. {
  78. out += "\xef\xbf\xbd";
  79. ++i;
  80. }
  81. }
  82. return out;
  83. }
  84. bool isSeparator (char c) noexcept { return c == '\\' || c == '/'; }
  85. // "C:/a\\b/" -> "c:/a/b" (for comparing paths: separators unified, letter case ignored for ASCII, no trailing separator)
  86. std::string comparable (const std::string& path)
  87. {
  88. std::string out;
  89. for (const auto ch : path)
  90. {
  91. const auto c = isSeparator (ch) ? '/' : ch;
  92. if (c == '/' && ! out.empty() && out.back() == '/')
  93. continue;
  94. out += (char) ((c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c);
  95. }
  96. while (out.size() > 1 && out.back() == '/')
  97. out.pop_back();
  98. return out;
  99. }
  100. } // namespace
  101. const char* const flFactoryToken = "%FLStudioFactoryData%";
  102. std::string expandFlSheetPath (const std::string& stored, const std::string& flFactoryData)
  103. {
  104. const std::string token (flFactoryToken);
  105. if (stored.size() < token.size() || comparable (stored.substr (0, token.size())) != comparable (token) || flFactoryData.empty())
  106. return stored;
  107. auto rest = stored.substr (token.size());
  108. while (! rest.empty() && isSeparator (rest.front()))
  109. rest.erase (rest.begin());
  110. auto root = flFactoryData;
  111. while (root.size() > 1 && isSeparator (root.back()))
  112. root.pop_back();
  113. // the root's own separator style (FL's backslashes become '/' under a POSIX root: macOS, Linux, a Wine prefix)
  114. const auto posix = root.find ('\\') == std::string::npos && root.find ('/') != std::string::npos;
  115. if (posix)
  116. for (auto& c : rest)
  117. if (c == '\\')
  118. c = '/';
  119. return rest.empty() ? root : root + (posix ? "/" : "\\") + rest;
  120. }
  121. std::string flSheetPath (const std::string& path, const std::string& flFactoryData)
  122. {
  123. if (path.empty() || flFactoryData.empty())
  124. return path;
  125. const auto root = comparable (flFactoryData), file = comparable (path);
  126. if (root.empty() || file.size() <= root.size() + 1 || file.compare (0, root.size(), root) != 0 || file[root.size()] != '/')
  127. return path;
  128. // the part of `path` that is the root (as comparable() reads it: doubled separators count once)
  129. std::size_t at = 0, n = 0;
  130. bool lastSlash = false;
  131. while (at < path.size() && n < root.size())
  132. {
  133. const auto slash = isSeparator (path[at]);
  134. if (! (slash && lastSlash))
  135. ++n;
  136. lastSlash = slash;
  137. ++at;
  138. }
  139. auto rest = path.substr (at);
  140. while (! rest.empty() && isSeparator (rest.front()))
  141. rest.erase (rest.begin());
  142. for (auto& c : rest)
  143. if (c == '/')
  144. c = '\\';
  145. return std::string (flFactoryToken) + "\\" + rest;
  146. }
  147. const char* moveName (int move) noexcept
  148. {
  149. switch (std::clamp (move, 0, moveCount - 1))
  150. {
  151. case freestyle: return "Freestyle";
  152. case waiting: return "Waiting";
  153. case stepping: return "Stepping";
  154. case jumping: return "Jumping";
  155. case zombie: return "Zombie";
  156. case waving: return "Waving";
  157. case hula: return "Hula";
  158. case windmill: return "Windmill";
  159. case flail: return "Flailing";
  160. case spin: return "Spinning";
  161. case held: return "Pose";
  162. }
  163. return "Freestyle";
  164. }
  165. std::vector<std::uint8_t> toState (const Settings& s)
  166. {
  167. std::ostringstream o;
  168. char colour[16];
  169. std::snprintf (colour, sizeof (colour), "%08x", s.colour);
  170. o << "LYNX dance 1\nmove=";
  171. if (s.sheet.empty() && s.move >= 0 && s.move < moveCount)
  172. o << moveIds[s.move];
  173. else
  174. o << std::clamp (s.move, 0, maxMoves - 1); // (a sheet's moves are its rows: a number)
  175. o << "\nmirrored=" << (s.mirrored ? 1 : 0) << "\nvisible=" << (s.visible ? 1 : 0) << "\nscale=" << s.scale << "\nspeed=" << s.speed
  176. << "\nx=" << s.x << "\ny=" << s.y << "\ncolour=" << colour << "\n";
  177. // (only when used, so the states of dancers without a sheet stay as they were)
  178. if (s.blend != Settings {}.blend)
  179. o << "blend=" << s.blend << "\n";
  180. // FL's display options (round 190bf; only when changed, so the states of dancers made before stay as they were)
  181. if (s.reflect != Settings {}.reflect)
  182. o << "reflect=" << s.reflect << "\n";
  183. if (! s.sync)
  184. o << "sync=0\n";
  185. if (! s.solid)
  186. o << "solid=0\n";
  187. if (! s.keepInFront)
  188. o << "front=0\n";
  189. if (! s.onDesktop)
  190. o << "desktop=0\n";
  191. if (! s.sheet.empty())
  192. {
  193. auto path = s.sheet;
  194. for (auto& c : path)
  195. if (c == '\n' || c == '\r')
  196. c = ' ';
  197. o << "sheet=" << path << "\n";
  198. }
  199. const auto t = o.str();
  200. return { t.begin(), t.end() };
  201. }
  202. std::optional<Settings> fromState (const std::vector<std::uint8_t>& state)
  203. {
  204. const std::string text (state.begin(), state.end());
  205. if (text.rfind ("LYNX dance", 0) != 0)
  206. return std::nullopt;
  207. Settings s;
  208. std::istringstream in (text);
  209. std::string line;
  210. std::getline (in, line);
  211. auto num = [] (const std::string& v, float lo, float hi, float fallback) {
  212. const auto f = std::strtof (v.c_str(), nullptr);
  213. return std::isfinite (f) ? std::clamp (f, lo, hi) : fallback;
  214. };
  215. while (std::getline (in, line))
  216. {
  217. if (! line.empty() && line.back() == '\r')
  218. line.pop_back();
  219. const auto eq = line.find ('=');
  220. if (eq == std::string::npos)
  221. continue;
  222. const auto key = line.substr (0, eq), value = line.substr (eq + 1);
  223. if (key == "move")
  224. {
  225. for (int m = 0; m < moveCount; ++m)
  226. if (value == moveIds[m])
  227. s.move = m;
  228. if (! value.empty() && value.find_first_not_of ("0123456789") == std::string::npos)
  229. s.move = std::clamp (std::atoi (value.c_str()), 0, maxMoves - 1);
  230. }
  231. else if (key == "blend")
  232. s.blend = num (value, 0.0f, 1.0f, Settings {}.blend);
  233. else if (key == "sheet")
  234. s.sheet = value;
  235. else if (key == "reflect")
  236. s.reflect = num (value, 0.0f, 1.0f, Settings {}.reflect);
  237. else if (key == "sync")
  238. s.sync = value != "0";
  239. else if (key == "solid")
  240. s.solid = value != "0";
  241. else if (key == "front")
  242. s.keepInFront = value != "0";
  243. else if (key == "desktop")
  244. s.onDesktop = value != "0";
  245. else if (key == "mirrored")
  246. s.mirrored = value != "0";
  247. else if (key == "visible")
  248. s.visible = value != "0";
  249. else if (key == "scale")
  250. s.scale = num (value, 0.25f, 3.0f, 1.0f);
  251. else if (key == "speed")
  252. s.speed = num (value, 0.125f, 4.0f, 1.0f);
  253. else if (key == "x")
  254. s.x = std::clamp (std::atoi (value.c_str()), -10000, 10000);
  255. else if (key == "y")
  256. s.y = std::clamp (std::atoi (value.c_str()), -10000, 10000);
  257. else if (key == "colour")
  258. s.colour = (std::uint32_t) std::strtoul (value.c_str(), nullptr, 16) | 0xff000000u;
  259. }
  260. return s;
  261. }
  262. std::optional<Settings> fromFl (const std::vector<std::uint8_t>& state, const std::string& flFactoryData)
  263. {
  264. if (state.size() < 40)
  265. return std::nullopt;
  266. auto i32 = [&state] (std::size_t at) {
  267. std::int32_t v = 0;
  268. std::memcpy (&v, state.data() + at, 4);
  269. return v;
  270. };
  271. const auto version = i32 (0);
  272. if (version < 1 || version > 16)
  273. return std::nullopt;
  274. Settings s;
  275. // params 0 … 6 (FL: move, mirrored, shown, blend /256, speed, x, y). The move is 0 = Freestyle, then the sheet's
  276. // rows; it is kept as it is (LYNX's own dancer clamps it when it draws).
  277. s.move = std::clamp ((int) i32 (4), 0, maxMoves - 1);
  278. s.mirrored = i32 (8) > 0;
  279. s.visible = i32 (12) > 0;
  280. s.blend = std::clamp ((float) i32 (16) / 256.0f, 0.0f, 1.0f);
  281. // FL's speed: 0.5 × (1 + |v| × 3 / 96) (or divided by it): LYNX keeps the ratio to the default 0.5
  282. const auto v = i32 (20);
  283. const auto d = 1.0f + (float) std::abs (v) * 3.0f / 96.0f;
  284. s.speed = std::clamp (v < 0 ? 1.0f / d : d, 0.125f, 4.0f);
  285. s.x = std::clamp ((int) i32 (24), -10000, 10000);
  286. s.y = std::clamp ((int) i32 (28), -10000, 10000);
  287. // the display options (round 190bf): "Reflect" (0 … 256, FL's default 64), then the four switches in FL's order
  288. // (Sync changes, Keep in front, On desktop, Solid; all on in a new Fruity Dance, fl190be dance.flp / dance2.flp)
  289. s.reflect = std::clamp ((float) i32 (32) / 256.0f, 0.0f, 1.0f);
  290. s.sync = state[36] != 0;
  291. s.keepInFront = state[37] != 0;
  292. s.onDesktop = state[38] != 0;
  293. s.solid = state[39] != 0;
  294. // version 2: after the display options (an int and four flags, 8 bytes) the sheet's file: a length byte (255: an
  295. // int follows with the length), then the characters; control characters at the end are dropped. Empty = FL's own.
  296. if (version >= 2 && state.size() > 40)
  297. {
  298. std::size_t at = 40;
  299. std::size_t length = state[at++];
  300. if (length == 0xff)
  301. {
  302. if (state.size() < at + 4)
  303. return s;
  304. length = (std::uint32_t) i32 (at);
  305. at += 4;
  306. }
  307. if (length <= state.size() - at)
  308. {
  309. std::string path ((const char*) state.data() + at, length);
  310. while (! path.empty() && (unsigned char) path.back() < 0x20)
  311. path.pop_back();
  312. // FL writes UTF-8 (fl190be: "Dançé.png" as C3 A7 / C3 A9, the length counting bytes) and a file inside its
  313. // own folder as %FLStudioFactoryData%\... (expanded with FL's folder; without one the path stays as it is,
  314. // a file that cannot be found: LYNX's dancer stands in)
  315. s.sheet = expandFlSheetPath (validUtf8OnlyText (path), flFactoryData);
  316. }
  317. }
  318. return s;
  319. }
  320. std::vector<std::uint8_t> toFl (const Settings& s, const std::string& flFactoryData)
  321. {
  322. std::vector<std::uint8_t> b;
  323. auto i32 = [&b] (std::int32_t v) {
  324. for (int k = 0; k < 4; ++k)
  325. b.push_back ((std::uint8_t) ((std::uint32_t) v >> (8 * k)));
  326. };
  327. i32 (2);
  328. i32 (std::clamp (s.move, 0, maxMoves - 1));
  329. i32 (s.mirrored ? 1 : 0);
  330. i32 (s.visible ? 1 : 0);
  331. i32 ((std::int32_t) std::lround (std::clamp (s.blend, 0.0f, 1.0f) * 256.0f));
  332. // the speed slider: -96 … 96 around FL's default (see fromFl)
  333. const auto ratio = std::clamp (s.speed, 0.25f, 4.0f);
  334. i32 ((std::int32_t) std::lround (ratio >= 1.0f ? (ratio - 1.0f) * 32.0f : -(1.0f / ratio - 1.0f) * 32.0f));
  335. i32 (s.x);
  336. i32 (s.y);
  337. // the display options: Reflect (0 … 256), then Sync changes, Keep in front, On desktop, Solid
  338. i32 ((std::int32_t) std::lround (std::clamp (s.reflect, 0.0f, 1.0f) * 256.0f));
  339. for (const auto on : { s.sync, s.keepInFront, s.onDesktop, s.solid })
  340. b.push_back (on ? 1 : 0);
  341. const auto sheet = flSheetPath (s.sheet, flFactoryData);
  342. const auto length = sheet.size();
  343. if (length < 0xff)
  344. b.push_back ((std::uint8_t) length);
  345. else
  346. {
  347. b.push_back (0xff);
  348. i32 ((std::int32_t) length);
  349. }
  350. b.insert (b.end(), sheet.begin(), sheet.end());
  351. return b;
  352. }
  353. Settings read (const std::vector<std::uint8_t>& state)
  354. {
  355. if (auto s = fromState (state))
  356. return *s;
  357. if (auto s = fromFl (state))
  358. return *s;
  359. return {};
  360. }
  361. KeyAction actionForKey (int key) noexcept
  362. {
  363. return actionForKey (key, moveCount);
  364. }
  365. KeyAction actionForKey (int key, int moves) noexcept
  366. {
  367. // FL fills its key table for the loaded sheet (FUN_0071a410): keys 59 … 59 + rows - 1 (at most 127) and
  368. // 48 … 48 - (rows - 1) (at least 0), then Hide / Show on 53 / 54 over whatever was there
  369. KeyAction a;
  370. moves = std::clamp (moves, 1, maxMoves);
  371. if (key == hideKey)
  372. a.kind = KeyAction::Kind::hide;
  373. else if (key == showKey)
  374. a.kind = KeyAction::Kind::show;
  375. else if (key >= firstMoveKey && key < firstMoveKey + moves && key <= 127)
  376. {
  377. a.kind = KeyAction::Kind::move;
  378. a.move = key - firstMoveKey;
  379. }
  380. else if (key <= firstMirrorKey && key > firstMirrorKey - moves && key >= 0)
  381. {
  382. a.kind = KeyAction::Kind::move;
  383. a.move = firstMirrorKey - key;
  384. a.mirrored = true;
  385. }
  386. else if (key == hideKey)
  387. a.kind = KeyAction::Kind::hide;
  388. else if (key == showKey)
  389. a.kind = KeyAction::Kind::show;
  390. return a;
  391. }
  392. Pose Pose::mix (const Pose& a, const Pose& b, float t) noexcept
  393. {
  394. auto m = [t] (float x, float y) { return x + (y - x) * t; };
  395. Pose p;
  396. p.x = m (a.x, b.x);
  397. p.y = m (a.y, b.y);
  398. p.lean = m (a.lean, b.lean);
  399. p.head = m (a.head, b.head);
  400. p.turn = m (a.turn, b.turn);
  401. p.squash = m (a.squash, b.squash);
  402. p.hipShift = m (a.hipShift, b.hipShift);
  403. p.tail = m (a.tail, b.tail);
  404. for (int i = 0; i < 2; ++i)
  405. {
  406. p.shoulder[(std::size_t) i] = m (a.shoulder[(std::size_t) i], b.shoulder[(std::size_t) i]);
  407. p.elbow[(std::size_t) i] = m (a.elbow[(std::size_t) i], b.elbow[(std::size_t) i]);
  408. p.hip[(std::size_t) i] = m (a.hip[(std::size_t) i], b.hip[(std::size_t) i]);
  409. p.knee[(std::size_t) i] = m (a.knee[(std::size_t) i], b.knee[(std::size_t) i]);
  410. }
  411. return p;
  412. }
  413. int freestyleMove (std::int64_t cycleIndex, std::uint32_t seed) noexcept
  414. {
  415. // two cycles per choice; Stepping … Spinning
  416. const auto h = mixBits ((std::uint32_t) (cycleIndex / 2) * 2654435761u ^ seed);
  417. return stepping + (int) (h % (std::uint32_t) (spin - stepping + 1));
  418. }
  419. Pose pose (int move, double cycles, std::uint32_t seed) noexcept
  420. {
  421. if (move == freestyle)
  422. {
  423. const auto index = (std::int64_t) std::floor (cycles);
  424. const auto now = freestyleMove (index, seed);
  425. const auto before = freestyleMove (index - 1, seed);
  426. const auto within = (float) (cycles - std::floor (cycles));
  427. if (now != before && (index % 2) == 0 && within < 0.25f) // a short blend into the new move
  428. return Pose::mix (pose (before, cycles, seed), pose (now, cycles, seed), smooth (within / 0.25f));
  429. return pose (now, cycles, seed);
  430. }
  431. const auto phase = (float) (cycles - std::floor (cycles)); // 0..1 within the cycle
  432. const auto s = std::sin (twoPi * phase), c = std::cos (twoPi * phase);
  433. const auto s2 = std::sin (2.0f * twoPi * phase);
  434. Pose p;
  435. // rest: arms down a little out, legs straight
  436. p.shoulder = { 0.25f, -0.25f };
  437. p.elbow = { 0.15f, -0.15f };
  438. p.hip = { 0.08f, -0.08f };
  439. switch (move)
  440. {
  441. case waiting:
  442. {
  443. const auto slow = (float) std::sin (twoPi * cycles * 0.25);
  444. p.y = 0.006f * s;
  445. p.lean = 0.03f * slow;
  446. p.head = 0.08f * slow;
  447. p.tail = 0.3f * s;
  448. p.shoulder = { 0.18f, -0.18f };
  449. // a foot taps on the beat
  450. p.knee = { 0.0f, phase < 0.3f ? -0.35f * std::sin (twoPi * phase / 0.6f) : 0.0f };
  451. p.hip[1] = phase < 0.3f ? 0.15f * std::sin (twoPi * phase / 0.6f) : -0.08f;
  452. break;
  453. }
  454. case stepping:
  455. {
  456. p.hipShift = 0.07f * s;
  457. p.x = 0.04f * s;
  458. p.y = 0.02f * std::abs (s2);
  459. p.lean = -0.08f * s;
  460. p.head = 0.1f * s;
  461. p.hip = { 0.12f + 0.18f * std::max (0.0f, s), -0.12f + 0.18f * std::min (0.0f, s) };
  462. p.knee = { -0.5f * std::max (0.0f, s), 0.5f * std::max (0.0f, -s) };
  463. p.shoulder = { 0.3f - 0.45f * s, -0.3f - 0.45f * s };
  464. p.elbow = { 0.6f, -0.6f };
  465. p.tail = -0.5f * s;
  466. break;
  467. }
  468. case jumping:
  469. {
  470. const auto up = std::abs (std::sin (0.5f * twoPi * phase * 2.0f)); // two hops a cycle
  471. const auto hop = up * up;
  472. p.y = 0.16f * hop;
  473. p.squash = 1.0f - 0.12f * (1.0f - up) * (1.0f - up);
  474. p.shoulder = { 0.5f + 2.2f * hop, -0.5f - 2.2f * hop };
  475. p.elbow = { 0.3f * (1.0f - hop), -0.3f * (1.0f - hop) };
  476. p.hip = { 0.2f, -0.2f };
  477. p.knee = { -0.9f * (1.0f - up), 0.9f * (1.0f - up) };
  478. p.tail = 0.8f * hop;
  479. break;
  480. }
  481. case zombie:
  482. {
  483. p.x = 0.03f * s;
  484. p.lean = 0.12f + 0.05f * s;
  485. p.head = 0.35f + 0.1f * c;
  486. p.shoulder = { 1.5f + 0.1f * s, -1.5f + 0.1f * c }; // arms out in front
  487. p.elbow = { 0.05f, -0.05f };
  488. p.hip = { 0.1f + 0.2f * std::max (0.0f, s), -0.1f + 0.2f * std::min (0.0f, s) };
  489. p.knee = { -0.3f * std::max (0.0f, s), 0.3f * std::max (0.0f, -s) };
  490. p.y = -0.01f;
  491. p.tail = 0.1f * s;
  492. break;
  493. }
  494. case waving:
  495. {
  496. p.lean = 0.06f * s;
  497. p.head = -0.12f + 0.08f * s;
  498. p.shoulder = { 2.6f, -0.9f }; // left arm up, right on the hip
  499. p.elbow = { 0.5f + 0.6f * s2, -1.9f };
  500. p.hipShift = 0.03f * s;
  501. p.y = 0.012f * std::abs (s);
  502. p.tail = 0.6f * s2;
  503. break;
  504. }
  505. case hula:
  506. {
  507. p.hipShift = 0.09f * s;
  508. p.y = 0.015f * c;
  509. p.lean = -0.12f * s;
  510. p.head = 0.12f * s;
  511. p.shoulder = { 1.5f + 0.25f * s, -1.5f + 0.25f * s }; // arms out, waving
  512. p.elbow = { 0.6f * c, -0.6f * c };
  513. p.knee = { -0.25f, 0.25f };
  514. p.hip = { 0.15f, -0.15f };
  515. p.tail = 0.9f * s;
  516. break;
  517. }
  518. case windmill:
  519. {
  520. const auto a = twoPi * phase;
  521. p.shoulder = { a, -1.2f + 0.8f * std::sin (a + 1.5f) }; // one arm circles
  522. p.elbow = { 0.0f, -0.4f };
  523. p.lean = 0.1f * std::sin (a);
  524. p.y = 0.03f * std::abs (std::sin (a));
  525. p.hip = { 0.2f, -0.2f };
  526. p.knee = { -0.3f * std::abs (s), 0.3f * std::abs (s) };
  527. p.tail = std::sin (a);
  528. break;
  529. }
  530. case flail:
  531. {
  532. // fast and a bit random: arms and legs everywhere
  533. auto jitter = [seed, cycles] (int k) {
  534. const auto t = (float) (cycles * 4.0 + k * 0.37);
  535. const auto i = (std::uint32_t) std::floor (t);
  536. const auto f = smooth (t - std::floor (t));
  537. auto r = [seed, k] (std::uint32_t n) { return (float) (mixBits (n * 7919u + (std::uint32_t) k * 104729u + seed) & 0xffff) / 65535.0f * 2.0f - 1.0f; };
  538. return r (i) + (r (i + 1) - r (i)) * f;
  539. };
  540. p.shoulder = { 1.5f + 1.3f * jitter (1), -1.5f + 1.3f * jitter (2) };
  541. p.elbow = { 1.0f * jitter (3), 1.0f * jitter (4) };
  542. p.hip = { 0.4f * jitter (5), 0.4f * jitter (6) };
  543. p.knee = { -0.6f * std::abs (jitter (7)), 0.6f * std::abs (jitter (8)) };
  544. p.lean = 0.15f * jitter (9);
  545. p.head = 0.3f * jitter (10);
  546. p.y = 0.05f * std::abs (jitter (11));
  547. p.x = 0.04f * jitter (12);
  548. p.tail = 1.2f * jitter (13);
  549. break;
  550. }
  551. case spin:
  552. {
  553. p.turn = std::cos (twoPi * phase);
  554. p.shoulder = { 1.55f, -1.55f }; // arms out
  555. p.elbow = { 0.1f * s, -0.1f * s };
  556. p.head = 0.15f * s;
  557. p.hip = { 0.05f, -0.05f };
  558. p.y = 0.01f * std::abs (s2);
  559. p.tail = 1.0f;
  560. break;
  561. }
  562. case held:
  563. {
  564. p.shoulder = { 2.4f, -2.4f }; // arms up in a V
  565. p.elbow = { -0.1f, 0.1f };
  566. p.hip = { 0.3f, -0.3f };
  567. p.head = -0.1f;
  568. p.y = 0.005f * s;
  569. p.tail = 0.4f;
  570. break;
  571. }
  572. default: break;
  573. }
  574. return p;
  575. }
  576. // ---------------------------------------------------------------------------------------------------------------
  577. // Sprite sheets in FL's format (issue #121; FL's code: REA_rodada190ba-121.md)
  578. // ---------------------------------------------------------------------------------------------------------------
  579. std::vector<std::string> sheetNames (const std::string& text)
  580. {
  581. std::vector<std::string> lines;
  582. std::size_t at = text.rfind ("\xef\xbb\xbf", 0) == 0 ? 3 : 0;
  583. while (at < text.size())
  584. {
  585. auto end = text.find_first_of ("\r\n", at);
  586. if (end == std::string::npos)
  587. end = text.size();
  588. lines.push_back (toUtf8 (text.substr (at, end - at)));
  589. at = end;
  590. if (at < text.size())
  591. at += text[at] == '\r' && at + 1 < text.size() && text[at + 1] == '\n' ? 2 : 1;
  592. }
  593. return lines;
  594. }
  595. std::vector<std::string> defaultSheetNames()
  596. {
  597. return { "Waiting", "Stepping", "Jumping", "Zombie", "Waving", "Hula", "Windmill", "Zitabata", "Dervish", "Held" };
  598. }
  599. std::string sheetNamesPath (const std::string& picturePath)
  600. {
  601. const auto slash = picturePath.find_last_of ("/\\");
  602. const auto dot = picturePath.find_last_of ('.');
  603. if (dot == std::string::npos || (slash != std::string::npos && dot < slash))
  604. return picturePath + ".txt";
  605. return picturePath.substr (0, dot) + ".txt";
  606. }
  607. SheetLayout sheetLayout (int width, int height, int nameLines) noexcept
  608. {
  609. SheetLayout l;
  610. l.rows = std::clamp (nameLines, 1, maxMoves);
  611. if (width < sheetColumns || height < l.rows)
  612. return l; // (FL stretches such a picture's canvas; nothing to show either way)
  613. l.frameWidth = width / sheetColumns;
  614. l.frameHeight = height / l.rows;
  615. l.valid = width % l.frameWidth == 0 && height % l.frameHeight == 0;
  616. return l;
  617. }
  618. int sheetMoveCount (int rows) noexcept { return std::clamp (rows, 1, maxMoves); }
  619. int sheetHeldRow (int rows) noexcept { return std::max (rows, 1) - 1; }
  620. std::vector<std::string> sheetMoveNames (const std::vector<std::string>& names)
  621. {
  622. std::vector<std::string> moves { "Freestyle" };
  623. for (std::size_t i = 0; i + 1 < names.size(); ++i)
  624. moves.push_back (names[i]);
  625. return moves;
  626. }
  627. std::vector<SheetKey> sheetKeys (const std::vector<std::string>& names)
  628. {
  629. std::vector<SheetKey> out;
  630. const auto moves = sheetMoveNames (names);
  631. for (int m = 0; m < (int) moves.size() && firstMoveKey + m <= 127; ++m)
  632. out.push_back ({ firstMoveKey + m, moves[(std::size_t) m] });
  633. return out;
  634. }
  635. std::string sheetHeldName (const std::vector<std::string>& names)
  636. {
  637. return names.empty() ? std::string() : names.back();
  638. }
  639. SheetFrame danceFrame (SheetAnimator& animator, double cycles, int rows, const Settings& settings, bool playing, bool held) noexcept
  640. {
  641. return animator.advance (cycles, rows, settings.move, settings.mirrored, playing, settings.blend, held, settings.sync);
  642. }
  643. SheetAnimator::SheetAnimator (std::uint32_t seed) noexcept : random (seed != 0 ? seed : 1) {}
  644. void SheetAnimator::draw (int rows) noexcept
  645. {
  646. // FL: Random (rows - 2) + 1 when the sheet has three rows or more, else 0
  647. random = mixBits (random + 0x9e3779b9u);
  648. freestyleRow = rows >= 3 ? 1 + (int) (random % (std::uint32_t) (rows - 2)) : 0;
  649. drawnFor = rows;
  650. }
  651. int SheetAnimator::rowFor (int rows, int move, bool playing) const noexcept
  652. {
  653. if (! playing)
  654. return 0;
  655. move = std::clamp (move, 0, rows - 1);
  656. return move == 0 ? freestyleRow : move - 1;
  657. }
  658. SheetFrame SheetAnimator::advance (double cycles, int rows, int move, bool mirrored, bool playing, float blend, bool held, bool sync) noexcept
  659. {
  660. rows = std::clamp (rows, 1, maxMoves);
  661. if (drawnFor != rows)
  662. draw (rows);
  663. if (! std::isfinite (cycles))
  664. cycles = 0.0;
  665. const auto phase = cycles - std::floor (cycles);
  666. if (phase <= lastPhase) // a cycle begins: the row changes now
  667. {
  668. shownRow = rowFor (rows, move, playing);
  669. shownMirrored = mirrored;
  670. draw (rows);
  671. }
  672. else if (! sync && std::clamp (move, 0, rows - 1) != 0)
  673. {
  674. // "Sync changes" off (FL: a move other than Freestyle shows at once, not at the next cycle's start)
  675. shownRow = rowFor (rows, move, playing);
  676. shownMirrored = mirrored;
  677. }
  678. lastPhase = phase;
  679. SheetFrame f;
  680. const auto steps = phase * sheetColumns;
  681. f.column = std::clamp ((int) std::floor (steps), 0, sheetColumns - 1);
  682. const auto within = (float) (steps - std::floor (steps));
  683. f.row = held ? sheetHeldRow (rows) : std::clamp (shownRow, 0, rows - 1);
  684. f.mirrored = ! held && shownMirrored; // (FL shows the held row unmirrored)
  685. const auto b = held ? 0.7f : std::clamp (blend, 0.0f, 1.0f);
  686. f.nextRow = f.row;
  687. f.nextColumn = (f.column + 1) % sheetColumns;
  688. if (b > 0.0f && within >= 1.0f - b)
  689. {
  690. // FL's steps of 1/255
  691. f.mix = std::clamp (std::round ((within - 1.0f + b) * 255.0f / b) / 255.0f, 0.0f, 1.0f);
  692. if (f.nextColumn == 0 && ! held)
  693. f.nextRow = std::clamp (rowFor (rows, move, playing), 0, rows - 1);
  694. }
  695. if (f.mix <= 0.0f)
  696. {
  697. f.nextRow = f.row;
  698. f.nextColumn = f.column;
  699. }
  700. return f;
  701. }
  702. // ---------------------------------------------------------------------------------------------------------------
  703. // The silent instrument
  704. // ---------------------------------------------------------------------------------------------------------------
  705. void Signals::push (int key) noexcept
  706. {
  707. const auto n = count.load (std::memory_order_relaxed);
  708. ring[n % ring.size()].store (key, std::memory_order_relaxed);
  709. count.store (n + 1, std::memory_order_release);
  710. }
  711. int Signals::pull (std::uint32_t& seen, int* keys, int max) const noexcept
  712. {
  713. const auto n = count.load (std::memory_order_acquire);
  714. auto from = seen;
  715. if (n - from > (std::uint32_t) ring.size())
  716. from = n - (std::uint32_t) ring.size();
  717. int got = 0;
  718. for (auto i = from; i != n && got < max; ++i)
  719. keys[got++] = ring[i % ring.size()].load (std::memory_order_relaxed);
  720. seen = n;
  721. return got;
  722. }
  723. namespace
  724. {
  725. class DanceInstrument final : public Instrument
  726. {
  727. public:
  728. void prepare (double) noexcept override {}
  729. void noteOn (int key, float) noexcept override { signals.push (key); }
  730. void noteOff (int) noexcept override {}
  731. void allNotesOff() noexcept override {}
  732. void render (float*, float*, int, float, float) noexcept override {}
  733. bool idle() const noexcept override { return true; } // (never a voice: its render can be skipped)
  734. Signals signals;
  735. };
  736. } // namespace
  737. std::unique_ptr<Instrument> makeInstrument()
  738. {
  739. return std::make_unique<DanceInstrument>();
  740. }
  741. Signals* signalsOf (Instrument* instrument) noexcept
  742. {
  743. auto* d = dynamic_cast<DanceInstrument*> (instrument);
  744. return d != nullptr ? &d->signals : nullptr;
  745. }
  746. } // namespace lynx::dance