CubismModel.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. /**
  2. * Copyright(c) Live2D Inc. All rights reserved.
  3. *
  4. * Use of this source code is governed by the Live2D Open Software license
  5. * that can be found at https://www.live2d.com/eula/live2d-open-software-license-agreement_en.html.
  6. */
  7. using Live2D.Cubism.Framework;
  8. using System;
  9. using UnityEngine;
  10. #if UNITY_2019_3_OR_NEWER
  11. using UnityEngine.LowLevel;
  12. using UnityEngine.PlayerLoop;
  13. #elif UNITY_2018_1_OR_NEWER
  14. using UnityEngine.Experimental.LowLevel;
  15. using UnityEngine.Experimental.PlayerLoop;
  16. #endif
  17. namespace Live2D.Cubism.Core
  18. {
  19. /// <summary>
  20. /// Runtime Cubism model.
  21. /// </summary>
  22. [ExecuteInEditMode, CubismDontMoveOnReimport]
  23. public sealed class CubismModel : MonoBehaviour
  24. {
  25. #region Delegates
  26. /// <summary>
  27. /// Handler for <see cref="CubismDynamicDrawableData"/>.
  28. /// </summary>
  29. /// <param name="sender">Model the dymanic data applies to.</param>
  30. /// <param name="data">New data.</param>
  31. public delegate void DynamicDrawableDataHandler(CubismModel sender, CubismDynamicDrawableData[] data);
  32. #endregion
  33. #region Events
  34. /// <summary>
  35. /// Event triggered if new <see cref="CubismDynamicDrawableData"/> is available for instance.
  36. /// </summary>
  37. public event DynamicDrawableDataHandler OnDynamicDrawableData;
  38. #endregion
  39. #region Factory Methods
  40. /// <summary>
  41. /// Instantiates a <see cref="CubismMoc"/>.
  42. /// </summary>
  43. /// <param name="moc">Cubism moc to instantiate.</param>
  44. /// <returns>Instance.</returns>
  45. public static CubismModel InstantiateFrom(CubismMoc moc)
  46. {
  47. // Return if argument is invalid.
  48. if (moc == null)
  49. {
  50. return null;
  51. }
  52. // Create model.
  53. var model = new GameObject(moc.name)
  54. .AddComponent<CubismModel>();
  55. // Initialize it by resetting it.
  56. model.Reset(moc);
  57. return model;
  58. }
  59. #endregion
  60. /// <summary>
  61. /// Resets a <see cref="CubismMoc"/> reference in <see cref="CubismModel"/>.
  62. /// </summary>
  63. /// <param name="model">Target Cubism model.</param>
  64. /// <param name="moc">Cubism moc to reset.</param>
  65. public static void ResetMocReference(CubismModel model, CubismMoc moc)
  66. {
  67. model.Moc = moc;
  68. }
  69. /// <summary>
  70. /// <see cref="Moc"/> backing field.
  71. /// </summary>
  72. [SerializeField, HideInInspector]
  73. private CubismMoc _moc;
  74. /// <summary>
  75. /// Moc the instance was instantiated from.
  76. /// </summary>
  77. public CubismMoc Moc
  78. {
  79. get { return _moc; }
  80. private set { _moc = value; }
  81. }
  82. /// <summary>
  83. /// TaskableModel for unmanaged backend.
  84. /// </summary>
  85. private CubismTaskableModel TaskableModel { get; set; }
  86. /// <summary>
  87. /// <see cref="Parameters"/> backing field.
  88. /// </summary>
  89. [NonSerialized]
  90. private CubismParameter[] _parameters;
  91. /// <summary>
  92. /// Drawables of model.
  93. /// </summary>
  94. public CubismParameter[] Parameters
  95. {
  96. get
  97. {
  98. if (_parameters == null)
  99. {
  100. Revive();
  101. }
  102. return _parameters;
  103. }
  104. private set { _parameters = value; }
  105. }
  106. /// <summary>
  107. /// <see cref="Parts"/> backing field.
  108. /// </summary>
  109. [NonSerialized]
  110. private CubismPart[] _parts;
  111. /// <summary>
  112. /// Drawables of model.
  113. /// </summary>
  114. public CubismPart[] Parts
  115. {
  116. get
  117. {
  118. if (_parts == null)
  119. {
  120. Revive();
  121. }
  122. return _parts;
  123. }
  124. private set { _parts = value; }
  125. }
  126. /// <summary>
  127. /// <see cref="Drawables"/> backing field.
  128. /// </summary>
  129. [NonSerialized]
  130. private CubismDrawable[] _drawables;
  131. /// <summary>
  132. /// Drawables of model.
  133. /// </summary>
  134. public CubismDrawable[] Drawables
  135. {
  136. get
  137. {
  138. if (_drawables == null)
  139. {
  140. Revive();
  141. }
  142. return _drawables;
  143. }
  144. private set { _drawables = value; }
  145. }
  146. /// <summary>
  147. /// <see cref="CanvasInformation"/> backing field.
  148. /// </summary>
  149. [NonSerialized]
  150. private CubismCanvasInformation _canvasInformation;
  151. /// <summary>
  152. /// Canvas information of model.
  153. /// </summary>
  154. public CubismCanvasInformation CanvasInformation
  155. {
  156. get
  157. {
  158. if (_canvasInformation == null)
  159. {
  160. Revive();
  161. }
  162. return _canvasInformation;
  163. }
  164. private set { _canvasInformation = value; }
  165. }
  166. /// <summary>
  167. /// Parameter store cache.
  168. /// </summary>
  169. CubismParameterStore _parameterStore;
  170. /// <summary>
  171. /// True if instance is revived.
  172. /// </summary>
  173. public bool IsRevived
  174. {
  175. get { return TaskableModel != null; }
  176. }
  177. /// <summary>
  178. /// True if instance can revive.
  179. /// </summary>
  180. private bool CanRevive
  181. {
  182. get { return Moc != null; }
  183. }
  184. #if UNITY_2018_1_OR_NEWER
  185. /// <summary>
  186. /// Model update functions for player loop.
  187. /// </summary>
  188. [NonSerialized]
  189. private static Action _modelUpdateFunctions;
  190. private bool WasAttachedModelUpdateFunction { get; set; }
  191. #endif
  192. /// <summary>
  193. /// True on the frame the instance was enabled.
  194. /// </summary>
  195. private bool WasJustEnabled { get; set; }
  196. /// <summary>
  197. /// Frame number last update was done.
  198. /// </summary>
  199. private int LastTick { get; set; }
  200. /// <summary>
  201. /// Revives instance.
  202. /// </summary>
  203. private void Revive()
  204. {
  205. // Return if already revive.
  206. if (IsRevived)
  207. {
  208. return;
  209. }
  210. // Return if revive isn't possible.
  211. if (!CanRevive)
  212. {
  213. return;
  214. }
  215. // Revive unmanaged model.
  216. TaskableModel = new CubismTaskableModel(Moc);
  217. // Revive proxies.
  218. Parameters = GetComponentsInChildren<CubismParameter>();
  219. Parts = GetComponentsInChildren<CubismPart>();
  220. Drawables = GetComponentsInChildren<CubismDrawable>();
  221. Parameters.Revive(TaskableModel.UnmanagedModel);
  222. Parts.Revive(TaskableModel.UnmanagedModel);
  223. Drawables.Revive(TaskableModel.UnmanagedModel);
  224. CanvasInformation = new CubismCanvasInformation(TaskableModel.UnmanagedModel);
  225. _parameterStore = GetComponent<CubismParameterStore>();
  226. }
  227. /// <summary>
  228. /// Initializes instance for first use.
  229. /// </summary>
  230. /// <param name="moc">Moc to instantiate from.</param>
  231. private void Reset(CubismMoc moc)
  232. {
  233. Moc = moc;
  234. name = moc.name;
  235. TaskableModel = new CubismTaskableModel(moc);
  236. // Create and initialize proxies.
  237. var parameters = CubismParameter.CreateParameters(TaskableModel.UnmanagedModel);
  238. var parts = CubismPart.CreateParts(TaskableModel.UnmanagedModel);
  239. var drawables = CubismDrawable.CreateDrawables(TaskableModel.UnmanagedModel);
  240. parameters.transform.SetParent(transform);
  241. parts.transform.SetParent(transform);
  242. drawables.transform.SetParent(transform);
  243. Parameters = parameters.GetComponentsInChildren<CubismParameter>();
  244. Parts = parts.GetComponentsInChildren<CubismPart>();
  245. Drawables = drawables.GetComponentsInChildren<CubismDrawable>();
  246. CanvasInformation = new CubismCanvasInformation(TaskableModel.UnmanagedModel);
  247. }
  248. /// <summary>
  249. /// Forces update.
  250. /// </summary>
  251. public void ForceUpdateNow()
  252. {
  253. WasJustEnabled = true;
  254. LastTick = -1;
  255. Revive();
  256. #if UNITY_2018_1_OR_NEWER
  257. OnModelUpdate();
  258. #else
  259. OnRenderObject();
  260. #endif
  261. }
  262. #if UNITY_2018_1_OR_NEWER
  263. /// <summary>
  264. /// Calls model update functions for player loop.
  265. /// </summary>
  266. private static void OnModelsUpdate()
  267. {
  268. if (_modelUpdateFunctions != null)
  269. {
  270. _modelUpdateFunctions.Invoke();
  271. }
  272. }
  273. /// <summary>
  274. /// Register the model update function into the player loop.
  275. /// </summary>
  276. [RuntimeInitializeOnLoadMethod]
  277. private static void RegisterCallbackFunction()
  278. {
  279. // Prepare the function for using player loop.
  280. var myPlayerLoopSystem = new PlayerLoopSystem()
  281. {
  282. type = typeof(CubismModel), // Identifier for Profiler Hierarchy view.
  283. updateDelegate = OnModelsUpdate // Register the function.
  284. };
  285. // Get the default player loop.
  286. var playerLoopSystem =
  287. #if UNITY_2019_3_OR_NEWER
  288. PlayerLoop.GetCurrentPlayerLoop();
  289. #else
  290. PlayerLoop.GetDefaultPlayerLoop();
  291. #endif
  292. var playerLoopIndex = -1;
  293. for (var i = 0; i < playerLoopSystem.subSystemList.Length; i++)
  294. {
  295. if (playerLoopSystem.subSystemList[i].type != typeof(PreLateUpdate))
  296. {
  297. continue;
  298. }
  299. playerLoopIndex = i;
  300. break;
  301. }
  302. if (playerLoopIndex < 0)
  303. {
  304. Debug.LogError("CubismModel : Failed to add processing to PlayerLoop.");
  305. return;
  306. }
  307. // Get the "PreLateUpdate" system.
  308. var playerLoopSubSystem = playerLoopSystem.subSystemList[playerLoopIndex];
  309. var subSystemList = playerLoopSubSystem.subSystemList;
  310. // Register the model update function after "PreLateUpdate" system.
  311. Array.Resize(ref subSystemList, subSystemList.Length + 1);
  312. subSystemList[subSystemList.Length - 1] = myPlayerLoopSystem;
  313. // Restore the "PreLateUpdate" sytem.
  314. playerLoopSubSystem.subSystemList = subSystemList;
  315. playerLoopSystem.subSystemList[playerLoopIndex] = playerLoopSubSystem;
  316. PlayerLoop.SetPlayerLoop(playerLoopSystem);
  317. }
  318. #endif
  319. #region Unity Event Handling
  320. /// <summary>
  321. /// Called by Unity. Triggers <see langword="this"/> to update.
  322. /// </summary>
  323. private void Update()
  324. {
  325. #if UNITY_2018_1_OR_NEWER
  326. if (!WasAttachedModelUpdateFunction)
  327. {
  328. _modelUpdateFunctions += OnModelUpdate;
  329. WasAttachedModelUpdateFunction = true;
  330. }
  331. #endif
  332. // Return on first frame enabled.
  333. if (WasJustEnabled)
  334. {
  335. return;
  336. }
  337. // Return unless revived.
  338. if (!IsRevived)
  339. {
  340. return;
  341. }
  342. // Return if backend is ticking.
  343. if (!TaskableModel.DidExecute)
  344. {
  345. return;
  346. }
  347. // Sync parameters back.
  348. TaskableModel.TryReadParameters(Parameters);
  349. // restore last frame parameters value and parts opacity.
  350. if (_parameterStore != null)
  351. {
  352. _parameterStore.RestoreParameters();
  353. }
  354. // Trigger event.
  355. if (OnDynamicDrawableData == null)
  356. {
  357. return;
  358. }
  359. OnDynamicDrawableData(this, TaskableModel.DynamicDrawableData);
  360. }
  361. /// <summary>
  362. /// Called by Unity. Blockingly updates <see langword="this"/> on first frame enabled; otherwise tries async update.
  363. /// </summary>
  364. private void OnRenderObject()
  365. {
  366. #if !UNITY_2018_1_OR_NEWER
  367. OnModelUpdate();
  368. #endif
  369. }
  370. /// <summary>
  371. /// Update model states.
  372. /// </summary>
  373. private void OnModelUpdate()
  374. {
  375. // Return unless revived.
  376. if (!IsRevived)
  377. {
  378. return;
  379. }
  380. // Return if already ticked this frame.
  381. if (LastTick == Time.frameCount && Application.isPlaying)
  382. {
  383. return;
  384. }
  385. LastTick = Time.frameCount;
  386. // Try to sync parameters and parts (without caring whether task is executing or not).
  387. TaskableModel.TryWriteParametersAndParts(Parameters, Parts);
  388. // Return if task is executing.
  389. if (TaskableModel.IsExecuting)
  390. {
  391. return;
  392. }
  393. // Force blocking update on first frame enabled.
  394. if (WasJustEnabled)
  395. {
  396. // Force sync update.
  397. TaskableModel.UpdateNow();
  398. // Unset condition.
  399. WasJustEnabled = false;
  400. // Fetch results by calling own 'Update()'.
  401. Update();
  402. return;
  403. }
  404. // Enqueue update task.
  405. TaskableModel.Update();
  406. }
  407. /// <summary>
  408. /// Called by Unity. Revives instance.
  409. /// </summary>
  410. private void OnEnable()
  411. {
  412. WasJustEnabled = true;
  413. Revive();
  414. }
  415. private void OnDisable()
  416. {
  417. #if UNITY_2018_1_OR_NEWER
  418. if (WasAttachedModelUpdateFunction)
  419. {
  420. _modelUpdateFunctions -= OnModelUpdate;
  421. WasAttachedModelUpdateFunction = false;
  422. }
  423. #endif
  424. }
  425. /// <summary>
  426. /// Called by Unity. Releases unmanaged memory.
  427. /// </summary>
  428. private void OnDestroy()
  429. {
  430. if (!IsRevived)
  431. {
  432. return;
  433. }
  434. TaskableModel.ReleaseUnmanaged();
  435. TaskableModel = null;
  436. }
  437. /// <summary>
  438. /// Called by Unity. Triggers <see cref="OnEnable"/>.
  439. /// </summary>
  440. private void OnValidate()
  441. {
  442. OnEnable();
  443. }
  444. #endregion
  445. }
  446. }