Assignment for RMIT Mixed Reality in 2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

843 lines
29 KiB

  1. // Amplify Shader Editor - Visual Shader Editing Tool
  2. // Copyright (c) Amplify Creations, Lda <info@amplify.pt>
  3. using System;
  4. using System.IO;
  5. using System.Security.Cryptography;
  6. using System.Collections.Generic;
  7. using UnityEngine;
  8. using UnityEditor;
  9. using System.Threading;
  10. using UnityEditor.VersionControl;
  11. namespace AmplifyShaderEditor
  12. {
  13. public enum ShaderLoadResult
  14. {
  15. LOADED,
  16. TEMPLATE_LOADED,
  17. FILE_NOT_FOUND,
  18. ASE_INFO_NOT_FOUND,
  19. UNITY_NATIVE_PATHS
  20. }
  21. public class Worker
  22. {
  23. public static readonly object locker = new object();
  24. public void DoWork()
  25. {
  26. while ( IOUtils.ActiveThread )
  27. {
  28. if ( IOUtils.SaveInThreadFlag )
  29. {
  30. IOUtils.SaveInThreadFlag = false;
  31. lock ( locker )
  32. {
  33. IOUtils.SaveInThreadShaderBody = IOUtils.ShaderCopywriteMessage + IOUtils.SaveInThreadShaderBody;
  34. // Add checksum
  35. string checksum = IOUtils.CreateChecksum( IOUtils.SaveInThreadShaderBody );
  36. IOUtils.SaveInThreadShaderBody += IOUtils.CHECKSUM + IOUtils.VALUE_SEPARATOR + checksum;
  37. // Write to disk
  38. StreamWriter fileWriter = new StreamWriter( IOUtils.SaveInThreadPathName );
  39. try
  40. {
  41. fileWriter.Write( IOUtils.SaveInThreadShaderBody );
  42. Debug.Log( "Saving complete" );
  43. }
  44. catch ( Exception e )
  45. {
  46. Debug.LogException( e );
  47. }
  48. finally
  49. {
  50. fileWriter.Close();
  51. }
  52. }
  53. }
  54. }
  55. Debug.Log( "Thread closed" );
  56. }
  57. }
  58. public static class IOUtils
  59. {
  60. public delegate void OnShaderAction( Shader shader, bool isTemplate, string type );
  61. public static OnShaderAction OnShaderSavedEvent;
  62. public static OnShaderAction OnShaderTypeChangedEvent;
  63. public static readonly string ShaderCopywriteMessage = "// Made with Amplify Shader Editor\n// Available at the Unity Asset Store - http://u3d.as/y3X \n";
  64. public static readonly string GrabPassEmpty = "\t\tGrabPass{ }\n";
  65. public static readonly string GrabPassBegin = "\t\tGrabPass{ \"";
  66. public static readonly string GrabPassEnd = "\" }\n";
  67. public static readonly string PropertiesBegin = "\tProperties\n\t{\n";
  68. public static readonly string PropertiesEnd = "\t}\n";
  69. public static readonly string PropertiesElement = "\t\t{0}\n";
  70. public static readonly string PropertiesElementsRaw = "{0}\n";
  71. public static readonly string PragmaTargetHeader = "\t\t#pragma target {0}\n";
  72. public static readonly string InstancedPropertiesHeader = "multi_compile_instancing";
  73. public static readonly string VirtualTexturePragmaHeader = "multi_compile _ _VT_SINGLE_MODE";
  74. public static readonly string InstancedPropertiesBegin = "UNITY_INSTANCING_CBUFFER_START({0})";
  75. public static readonly string InstancedPropertiesEnd = "UNITY_INSTANCING_CBUFFER_END";
  76. public static readonly string InstancedPropertiesElement = "UNITY_DEFINE_INSTANCED_PROP({0}, {1})";
  77. public static readonly string InstancedPropertiesData = "UNITY_ACCESS_INSTANCED_PROP({0})";
  78. public static readonly string DotsInstancedPropertiesData = "\tUNITY_DOTS_INSTANCED_PROP({0}, {1})";
  79. public static readonly string DotsInstancedDefinesData = "#define {1} UNITY_ACCESS_DOTS_INSTANCED_PROP_FROM_MACRO({0} , Metadata_{1})";
  80. public static readonly string LWSRPInstancedPropertiesBegin = "UNITY_INSTANCING_BUFFER_START({0})";
  81. public static readonly string LWSRPInstancedPropertiesEnd = "UNITY_INSTANCING_BUFFER_END({0})";
  82. public static readonly string LWSRPInstancedPropertiesElement = "UNITY_DEFINE_INSTANCED_PROP({0}, {1})";
  83. public static readonly string LWSRPInstancedPropertiesData = "UNITY_ACCESS_INSTANCED_PROP({0},{1})";
  84. public static readonly string SRPCBufferPropertiesBegin = "CBUFFER_START( UnityPerMaterial )";//"CBUFFER_START({0})";
  85. public static readonly string SRPCBufferPropertiesEnd = "CBUFFER_END";
  86. public static readonly string InstancedPropertiesBeginTabs = "\t\t"+ InstancedPropertiesBegin + "\n";
  87. public static readonly string InstancedPropertiesEndTabs = "\t\t"+ InstancedPropertiesEnd + "\n";
  88. public static readonly string InstancedPropertiesElementTabs = "\t\t\t"+ InstancedPropertiesElement + "\n";
  89. public static readonly string MetaBegin = "defaultTextures:";
  90. public static readonly string MetaEnd = "userData:";
  91. public static readonly string ShaderBodyBegin = "/*ASEBEGIN";
  92. public static readonly string ShaderBodyEnd = "ASEEND*/";
  93. //public static readonly float CurrentVersionFlt = 0.4f;
  94. //public static readonly string CurrentVersionStr = "Version=" + CurrentVersionFlt;
  95. public static readonly string CHECKSUM = "//CHKSM";
  96. public static readonly string LAST_OPENED_OBJ_ID = "ASELASTOPENOBJID";
  97. public static readonly string MAT_CLIPBOARD_ID = "ASEMATCLIPBRDID";
  98. public static readonly char FIELD_SEPARATOR = ';';
  99. public static readonly char VALUE_SEPARATOR = '=';
  100. public static readonly char LINE_TERMINATOR = '\n';
  101. public static readonly char VECTOR_SEPARATOR = ',';
  102. public static readonly char FLOAT_SEPARATOR = '.';
  103. public static readonly char CLIPBOARD_DATA_SEPARATOR = '|';
  104. public static readonly char MATRIX_DATA_SEPARATOR = '|';
  105. public readonly static string NO_TEXTURES = "<None>";
  106. public static readonly string SaveShaderStr = "Please enter shader name to save";
  107. public static readonly string FloatifyStr = ".0";
  108. // Node parameter names
  109. public const string NodeParam = "Node";
  110. public const string NodePosition = "Position";
  111. public const string NodeId = "Id";
  112. public const string NodeType = "Type";
  113. public const string WireConnectionParam = "WireConnection";
  114. public static readonly uint NodeTypeId = 1;
  115. public static readonly int InNodeId = 1;
  116. public static readonly int InPortId = 2;
  117. public static readonly int OutNodeId = 3;
  118. public static readonly int OutPortId = 4;
  119. public readonly static string DefaultASEDirtyCheckName = "__dirty";
  120. public readonly static string DefaultASEDirtyCheckProperty = "[HideInInspector] " + DefaultASEDirtyCheckName + "( \"\", Int ) = 1";
  121. public readonly static string DefaultASEDirtyCheckUniform = "uniform int " + DefaultASEDirtyCheckName + " = 1;";
  122. public readonly static string MaskClipValueName = "_Cutoff";
  123. public readonly static string MaskClipValueProperty = MaskClipValueName + "( \"{0}\", Float ) = {1}";
  124. public readonly static string MaskClipValueUniform = "uniform float " + MaskClipValueName + " = {0};";
  125. public readonly static string ChromaticAberrationProperty = "_ChromaticAberration";
  126. //public static readonly string ASEFolderGUID = "daca988099666ec40aaa2cde22bb4935";
  127. //public static string ASEResourcesPath = "/Plugins/EditorResources/";
  128. //public static string ASEFolderPath;
  129. //public static bool IsShaderFunctionWindow = false;
  130. public static int DefaultASEDirtyCheckId;
  131. // this is to be used in combination with AssetDatabase.GetAssetPath, both of these include the Assets/ path so we need to remove from one of them
  132. public static string dataPath;
  133. public static string EditorResourcesGUID = "0932db7ec1402c2489679c4b72eab5eb";
  134. public static string GraphBgTextureGUID = "881c304491028ea48b5027ac6c62cf73";
  135. public static string GraphFgTextureGUID = "8c4a7fca2884fab419769ccc0355c0c1";
  136. public static string WireTextureGUID = "06e687f68dd96f0448c6d8217bbcf608";
  137. public static string MasterNodeOnTextureGUID = "26c64fcee91024a49980ea2ee9d1a2fb";
  138. public static string MasterNodeOffTextureGUID = "712aee08d999c16438e2d694f42428e8";
  139. public static string GPUInstancedOnTextureGUID = "4b0c2926cc71c5846ae2a29652d54fb6";
  140. public static string GPUInstancedOffTextureGUID = "486c7766baaf21b46afb63c1121ef03e";
  141. public static string MainSkinGUID = "57482289c346f104a8162a3a79aaff9d";
  142. public static string UpdateOutdatedGUID = "cce638be049286c41bcbd0a26c356b18";
  143. public static string UpdateOFFGUID = "99d70ac09b4db9742b404c3f92d8564b";
  144. public static string UpdateUpToDatedGUID = "ce30b12fbb3223746bcfef9ea82effe3";
  145. public static string LiveOffGUID = "bb16faf366bcc6c4fbf0d7666b105354";
  146. public static string LiveOnGUID = "6a0ae1d7892333142aeb09585572202c";
  147. public static string LivePendingGUID = "e3182200efb67114eb5050f8955e1746";
  148. public static string CleanupOFFGUID = "f62c0c3a5ddcd844e905fb2632fdcb15";
  149. public static string CleanUpOnGUID = "615d853995cf2344d8641fd19cb09b5d";
  150. public static string TakeScreenshotOFFGUID = "7587de2e3bec8bf4d973109524ccc6b1";
  151. public static string TakeScreenshotONGUID = "7587de2e3bec8bf4d973109524ccc6b1";
  152. public static string ShareOFFGUID = "bc5bd469748466a459badfab23915cb0";
  153. public static string ShareONGUID = "bc5bd469748466a459badfab23915cb0";
  154. public static string OpenSourceCodeOFFGUID = "f7e8834b42791124095a8b7f2d4daac2";
  155. public static string OpenSourceCodeONGUID = "8b114792ff84f6546880c031eda42bc0";
  156. public static string FocusNodeGUID = "da673e6179c67d346abb220a6935e359";
  157. public static string FitViewGUID = "1def740f2314c6b4691529cadeee2e9c";
  158. public static string ShowInfoWindowGUID = "77af20044e9766840a6be568806dc22e";
  159. public static string ShowTipsWindowGUID = "066674048bbb1e64e8cdcc6c3b4abbeb";
  160. public static string ShowConsoleWindowGUID = "9a81d7df8e62c044a9d1cada0c8a2131";
  161. public static Dictionary<string, string> NodeTypeReplacer = new Dictionary<string, string>()
  162. {
  163. {"AmplifyShaderEditor.RotateAboutAxis", "AmplifyShaderEditor.RotateAboutAxisNode"},
  164. {"GlobalArrayNode", "AmplifyShaderEditor.GlobalArrayNode"},
  165. {"AmplifyShaderEditor.SimpleMaxOp", "AmplifyShaderEditor.SimpleMaxOpNode"},
  166. {"AmplifyShaderEditor.SimpleMinNode", "AmplifyShaderEditor.SimpleMinOpNode"},
  167. {"AmplifyShaderEditor.TFHCRemap", "AmplifyShaderEditor.TFHCRemapNode"},
  168. {"AmplifyShaderEditor.TFHCPixelateUV", "AmplifyShaderEditor.TFHCPixelate"},
  169. {"AmplifyShaderEditor.VirtualTexturePropertyNode", "AmplifyShaderEditor.VirtualTextureObject"}
  170. };
  171. private static readonly string AmplifyShaderEditorDefineSymbol = "AMPLIFY_SHADER_EDITOR";
  172. /////////////////////////////////////////////////////////////////////////////
  173. // THREAD IO UTILS
  174. public static bool SaveInThreadFlag = false;
  175. public static string SaveInThreadShaderBody;
  176. public static string SaveInThreadPathName;
  177. public static Thread SaveInThreadMainThread;
  178. public static bool ActiveThread = true;
  179. private static bool UseSaveThread = false;
  180. private static bool Initialized = false;
  181. public static bool FunctionNodeChanged = false;
  182. public static List<AmplifyShaderEditorWindow> AllOpenedWindows = new List<AmplifyShaderEditorWindow>();
  183. public static void StartSaveThread( string shaderBody, string pathName )
  184. {
  185. if( Provider.enabled && Provider.isActive )
  186. {
  187. Asset loadedAsset = Provider.GetAssetByPath( FileUtil.GetProjectRelativePath( pathName ) );
  188. if( loadedAsset != null )
  189. {
  190. //Task statusTask = Provider.Status( loadedAsset );
  191. //statusTask.Wait();
  192. //if( Provider.CheckoutIsValid( statusTask.assetList[ 0 ] ) )
  193. {
  194. Task checkoutTask = Provider.Checkout( loadedAsset, CheckoutMode.Both );
  195. checkoutTask.Wait();
  196. }
  197. }
  198. }
  199. if( UseSaveThread )
  200. {
  201. if ( !SaveInThreadFlag )
  202. {
  203. if ( SaveInThreadMainThread == null )
  204. {
  205. Worker worker = new Worker();
  206. SaveInThreadMainThread = new Thread( worker.DoWork );
  207. SaveInThreadMainThread.Start();
  208. Debug.Log( "Thread created" );
  209. }
  210. SaveInThreadShaderBody = shaderBody;
  211. SaveInThreadPathName = pathName;
  212. SaveInThreadFlag = true;
  213. }
  214. }
  215. else
  216. {
  217. SaveTextfileToDisk( shaderBody, pathName );
  218. }
  219. }
  220. ////////////////////////////////////////////////////////////////////////////
  221. public static void SetAmplifyDefineSymbolOnBuildTargetGroup( BuildTargetGroup targetGroup )
  222. {
  223. string currData = PlayerSettings.GetScriptingDefineSymbolsForGroup( targetGroup );
  224. if ( !currData.Contains( AmplifyShaderEditorDefineSymbol ) )
  225. {
  226. if ( string.IsNullOrEmpty( currData ) )
  227. {
  228. PlayerSettings.SetScriptingDefineSymbolsForGroup( targetGroup, AmplifyShaderEditorDefineSymbol );
  229. }
  230. else
  231. {
  232. if ( !currData[ currData.Length - 1 ].Equals( ';' ) )
  233. {
  234. currData += ';';
  235. }
  236. currData += AmplifyShaderEditorDefineSymbol;
  237. PlayerSettings.SetScriptingDefineSymbolsForGroup( targetGroup, currData );
  238. }
  239. }
  240. }
  241. public static void RemoveAmplifyDefineSymbolOnBuildTargetGroup( BuildTargetGroup targetGroup )
  242. {
  243. string currData = PlayerSettings.GetScriptingDefineSymbolsForGroup( targetGroup );
  244. if( currData.Contains( AmplifyShaderEditorDefineSymbol ) )
  245. {
  246. currData = currData.Replace( AmplifyShaderEditorDefineSymbol + ";", "" );
  247. currData = currData.Replace( ";" + AmplifyShaderEditorDefineSymbol, "" );
  248. currData = currData.Replace( AmplifyShaderEditorDefineSymbol, "" );
  249. PlayerSettings.SetScriptingDefineSymbolsForGroup( targetGroup, currData );
  250. }
  251. }
  252. public static void Init()
  253. {
  254. if ( !Initialized )
  255. {
  256. Initialized = true;
  257. if( EditorPrefs.GetBool( Preferences.PrefDefineSymbol, true ) )
  258. SetAmplifyDefineSymbolOnBuildTargetGroup( EditorUserBuildSettings.selectedBuildTargetGroup );
  259. //Array BuildTargetGroupValues = Enum.GetValues( typeof( BuildTargetGroup ));
  260. //for ( int i = 0; i < BuildTargetGroupValues.Length; i++ )
  261. //{
  262. // if( i != 0 && i != 15 && i != 16 )
  263. // SetAmplifyDefineSymbolOnBuildTargetGroup( ( BuildTargetGroup ) BuildTargetGroupValues.GetValue( i ) );
  264. //}
  265. DefaultASEDirtyCheckId = Shader.PropertyToID( DefaultASEDirtyCheckName );
  266. dataPath = Application.dataPath.Remove( Application.dataPath.Length - 6 );
  267. //ASEFolderPath = AssetDatabase.GUIDToAssetPath( ASEFolderGUID );
  268. //ASEResourcesPath = ASEFolderPath + ASEResourcesPath;
  269. }
  270. }
  271. public static void DumpTemplateManagers()
  272. {
  273. for( int i = 0; i < AllOpenedWindows.Count; i++ )
  274. {
  275. if( AllOpenedWindows[ i ].TemplatesManagerInstance != null )
  276. {
  277. Debug.Log( AllOpenedWindows[ i ].titleContent.text + ": " + AllOpenedWindows[ i ].TemplatesManagerInstance.GetInstanceID() );
  278. }
  279. }
  280. }
  281. public static TemplatesManager FirstValidTemplatesManager
  282. {
  283. get
  284. {
  285. for( int i = 0; i < AllOpenedWindows.Count; i++ )
  286. {
  287. if( AllOpenedWindows[ i ].TemplatesManagerInstance != null )
  288. {
  289. return AllOpenedWindows[ i ].TemplatesManagerInstance;
  290. }
  291. }
  292. return null;
  293. }
  294. }
  295. public static void UpdateSFandRefreshWindows( AmplifyShaderFunction function )
  296. {
  297. for( int i = 0; i < AllOpenedWindows.Count; i++ )
  298. {
  299. AllOpenedWindows[ i ].LateRefreshAvailableNodes();
  300. if( AllOpenedWindows[ i ].IsShaderFunctionWindow )
  301. {
  302. if( AllOpenedWindows[ i ].OpenedShaderFunction == function )
  303. {
  304. AllOpenedWindows[ i ].UpdateTabTitle();
  305. }
  306. }
  307. }
  308. }
  309. public static void UpdateIO()
  310. {
  311. int windowCount = AllOpenedWindows.Count;
  312. if ( windowCount == 0 )
  313. {
  314. EditorApplication.update -= IOUtils.UpdateIO;
  315. return;
  316. }
  317. for ( int i = 0; i < AllOpenedWindows.Count; i++ )
  318. {
  319. if ( AllOpenedWindows[i] == EditorWindow.focusedWindow )
  320. {
  321. UIUtils.CurrentWindow = AllOpenedWindows[ i ];
  322. }
  323. if( FunctionNodeChanged )
  324. AllOpenedWindows[ i ].CheckFunctions = true;
  325. if ( AllOpenedWindows[ i ] == null )
  326. {
  327. AllOpenedWindows.RemoveAt( i );
  328. i--;
  329. }
  330. }
  331. if ( FunctionNodeChanged )
  332. FunctionNodeChanged = false;
  333. }
  334. public static void Destroy()
  335. {
  336. ActiveThread = false;
  337. if ( SaveInThreadMainThread != null )
  338. {
  339. SaveInThreadMainThread.Abort();
  340. SaveInThreadMainThread = null;
  341. }
  342. }
  343. public static void GetShaderName( out string shaderName, out string fullPathname, string defaultName, string customDatapath )
  344. {
  345. string currDatapath = String.IsNullOrEmpty( customDatapath ) ? Application.dataPath : customDatapath;
  346. fullPathname = EditorUtility.SaveFilePanelInProject( "Select Shader to save", defaultName, "shader", SaveShaderStr, currDatapath );
  347. if ( !String.IsNullOrEmpty( fullPathname ) )
  348. {
  349. shaderName = fullPathname.Remove( fullPathname.Length - 7 ); // -7 remove .shader extension
  350. string[] subStr = shaderName.Split( '/' );
  351. if ( subStr.Length > 0 )
  352. {
  353. shaderName = subStr[ subStr.Length - 1 ]; // Remove pathname
  354. }
  355. }
  356. else
  357. {
  358. shaderName = string.Empty;
  359. }
  360. }
  361. public static void AddTypeToString( ref string myString, string typeName )
  362. {
  363. myString += typeName;
  364. }
  365. public static void AddFieldToString( ref string myString, string fieldName, object fieldValue )
  366. {
  367. myString += FIELD_SEPARATOR + fieldName + VALUE_SEPARATOR + fieldValue;
  368. }
  369. public static void AddFieldValueToString( ref string myString, object fieldValue )
  370. {
  371. myString += FIELD_SEPARATOR + fieldValue.ToString();
  372. }
  373. public static void AddLineTerminator( ref string myString )
  374. {
  375. myString += LINE_TERMINATOR;
  376. }
  377. public static string CreateChecksum( string buffer )
  378. {
  379. SHA1 sha1 = SHA1.Create();
  380. byte[] buf = System.Text.Encoding.UTF8.GetBytes( buffer );
  381. byte[] hash = sha1.ComputeHash( buf, 0, buf.Length );
  382. string hashstr = BitConverter.ToString( hash ).Replace( "-", "" );
  383. return hashstr;
  384. }
  385. public static void SaveTextfileToDisk( string shaderBody, string pathName, bool addAdditionalInfo = true )
  386. {
  387. if ( addAdditionalInfo )
  388. {
  389. shaderBody = ShaderCopywriteMessage + shaderBody;
  390. // Add checksum
  391. string checksum = CreateChecksum( shaderBody );
  392. shaderBody += CHECKSUM + VALUE_SEPARATOR + checksum;
  393. }
  394. // Write to disk
  395. StreamWriter fileWriter = new StreamWriter( pathName );
  396. try
  397. {
  398. fileWriter.Write( shaderBody );
  399. }
  400. catch ( Exception e )
  401. {
  402. Debug.LogException( e );
  403. }
  404. finally
  405. {
  406. fileWriter.Close();
  407. }
  408. }
  409. public static string AddAdditionalInfo( string shaderBody )
  410. {
  411. shaderBody = ShaderCopywriteMessage + shaderBody;
  412. string checksum = CreateChecksum( shaderBody );
  413. shaderBody += CHECKSUM + VALUE_SEPARATOR + checksum;
  414. return shaderBody;
  415. }
  416. public static string LoadTextFileFromDisk( string pathName )
  417. {
  418. string result = string.Empty;
  419. if ( !string.IsNullOrEmpty( pathName ) && File.Exists( pathName ) )
  420. {
  421. StreamReader fileReader = null;
  422. try
  423. {
  424. fileReader = new StreamReader( pathName );
  425. result = fileReader.ReadToEnd();
  426. }
  427. catch ( Exception e )
  428. {
  429. Debug.LogException( e );
  430. }
  431. finally
  432. {
  433. if( fileReader != null)
  434. fileReader.Close();
  435. }
  436. }
  437. return result;
  438. }
  439. public static bool IsASEShader( Shader shader )
  440. {
  441. string datapath = AssetDatabase.GetAssetPath( shader );
  442. if ( UIUtils.IsUnityNativeShader( datapath ) )
  443. {
  444. return false;
  445. }
  446. string buffer = LoadTextFileFromDisk( datapath );
  447. if ( String.IsNullOrEmpty( buffer ) || !IOUtils.HasValidShaderBody( ref buffer ) )
  448. {
  449. return false;
  450. }
  451. return true;
  452. }
  453. public static bool IsShaderFunction( string functionInfo )
  454. {
  455. string buffer = functionInfo;
  456. if ( String.IsNullOrEmpty( buffer ) || !IOUtils.HasValidShaderBody( ref buffer ) )
  457. {
  458. return false;
  459. }
  460. return true;
  461. }
  462. public static bool HasValidShaderBody( ref string shaderBody )
  463. {
  464. int shaderBodyBeginId = shaderBody.IndexOf( ShaderBodyBegin );
  465. if ( shaderBodyBeginId > -1 )
  466. {
  467. int shaderBodyEndId = shaderBody.IndexOf( ShaderBodyEnd );
  468. return ( shaderBodyEndId > -1 && shaderBodyEndId > shaderBodyBeginId );
  469. }
  470. return false;
  471. }
  472. public static int[] AllIndexesOf( this string str, string substr, bool ignoreCase = false )
  473. {
  474. if ( string.IsNullOrEmpty( str ) || string.IsNullOrEmpty( substr ) )
  475. {
  476. throw new ArgumentException( "String or substring is not specified." );
  477. }
  478. List<int> indexes = new List<int>();
  479. int index = 0;
  480. while ( ( index = str.IndexOf( substr, index, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal ) ) != -1 )
  481. {
  482. indexes.Add( index++ );
  483. }
  484. return indexes.ToArray();
  485. }
  486. public static void AddFunctionHeader( ref string function, string header )
  487. {
  488. function += "\t\t" + header + "\n\t\t{\n";
  489. }
  490. public static void AddSingleLineFunction( ref string function, string header )
  491. {
  492. function += "\t\t" + header;
  493. }
  494. public static void AddFunctionLine( ref string function, string line )
  495. {
  496. function += "\t\t\t" + line + "\n";
  497. }
  498. public static void CloseFunctionBody( ref string function )
  499. {
  500. function += "\t\t}\n";
  501. }
  502. public static string CreateFullFunction( string header, params string[] functionLines )
  503. {
  504. string result = string.Empty;
  505. AddFunctionHeader( ref result, header );
  506. for ( int i = 0; i > functionLines.Length; i++ )
  507. {
  508. AddFunctionLine( ref result, functionLines[ i ] );
  509. }
  510. CloseFunctionBody( ref result );
  511. return result;
  512. }
  513. public static string CreateCodeComments( bool forceForwardSlash, params string[] comments )
  514. {
  515. string finalComment = string.Empty;
  516. if ( comments.Length == 1 )
  517. {
  518. finalComment = "//" + comments[ 0 ];
  519. }
  520. else
  521. {
  522. if ( forceForwardSlash )
  523. {
  524. for ( int i = 0; i < comments.Length; i++ )
  525. {
  526. finalComment += "//" + comments[ i ];
  527. if ( i < comments.Length - 1 )
  528. {
  529. finalComment += "\n\t\t\t";
  530. }
  531. }
  532. }
  533. else
  534. {
  535. finalComment = "/*";
  536. for ( int i = 0; i < comments.Length; i++ )
  537. {
  538. if ( i != 0 )
  539. finalComment += "\t\t\t";
  540. finalComment += comments[ i ];
  541. if ( i < comments.Length - 1 )
  542. finalComment += "\n";
  543. }
  544. finalComment += "*/";
  545. }
  546. }
  547. return finalComment;
  548. }
  549. public static string GetUVChannelDeclaration( string uvName, int channelId, int set )
  550. {
  551. string uvSetStr = ( set == 0 ) ? "uv" : "uv" + Constants.AvailableUVSetsStr[ set ];
  552. return "float2 " + uvSetStr + uvName /*+ " : TEXCOORD" + channelId*/;
  553. }
  554. public static string GetUVChannelName( string uvName, int set )
  555. {
  556. string uvSetStr = ( set == 0 ) ? "uv" : "uv" + Constants.AvailableUVSetsStr[ set ];
  557. return uvSetStr + uvName;
  558. }
  559. public static string GetVertexUVChannelName( int set )
  560. {
  561. string uvSetStr = ( set == 0 ) ? "texcoord" : ( "texcoord" + set.ToString() );
  562. return uvSetStr;
  563. }
  564. public static string Floatify( float value )
  565. {
  566. return ( value % 1 ) != 0 ? value.ToString() : ( value.ToString() + FloatifyStr );
  567. }
  568. public static string Vector2ToString( Vector2 data )
  569. {
  570. return data.x.ToString() + VECTOR_SEPARATOR + data.y.ToString();
  571. }
  572. public static string Vector3ToString( Vector3 data )
  573. {
  574. return data.x.ToString() + VECTOR_SEPARATOR + data.y.ToString() + VECTOR_SEPARATOR + data.z.ToString();
  575. }
  576. public static string Vector4ToString( Vector4 data )
  577. {
  578. return data.x.ToString() + VECTOR_SEPARATOR + data.y.ToString() + VECTOR_SEPARATOR + data.z.ToString() + VECTOR_SEPARATOR + data.w.ToString();
  579. }
  580. public static string ColorToString( Color data )
  581. {
  582. return data.r.ToString() + VECTOR_SEPARATOR + data.g.ToString() + VECTOR_SEPARATOR + data.b.ToString() + VECTOR_SEPARATOR + data.a.ToString();
  583. }
  584. public static string Matrix3x3ToString( Matrix4x4 matrix )
  585. {
  586. return matrix[ 0, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 0, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 0, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR +
  587. matrix[ 1, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 1, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 1, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR +
  588. matrix[ 2, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 2, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 2, 2 ].ToString();
  589. }
  590. public static string Matrix4x4ToString( Matrix4x4 matrix )
  591. {
  592. return matrix[ 0, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 0, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 0, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 0, 3 ].ToString() + IOUtils.VECTOR_SEPARATOR +
  593. matrix[ 1, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 1, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 1, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 1, 3 ].ToString() + IOUtils.VECTOR_SEPARATOR +
  594. matrix[ 2, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 2, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 2, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 2, 3 ].ToString() + IOUtils.VECTOR_SEPARATOR +
  595. matrix[ 3, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 3, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 3, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + matrix[ 3, 3 ].ToString();
  596. }
  597. public static Vector2 StringToVector2( string data )
  598. {
  599. string[] parsedData = data.Split( VECTOR_SEPARATOR );
  600. if ( parsedData.Length >= 2 )
  601. {
  602. return new Vector2( Convert.ToSingle( parsedData[ 0 ] ),
  603. Convert.ToSingle( parsedData[ 1 ] ) );
  604. }
  605. return Vector2.zero;
  606. }
  607. public static Vector3 StringToVector3( string data )
  608. {
  609. string[] parsedData = data.Split( VECTOR_SEPARATOR );
  610. if ( parsedData.Length >= 3 )
  611. {
  612. return new Vector3( Convert.ToSingle( parsedData[ 0 ] ),
  613. Convert.ToSingle( parsedData[ 1 ] ),
  614. Convert.ToSingle( parsedData[ 2 ] ) );
  615. }
  616. return Vector3.zero;
  617. }
  618. public static Vector4 StringToVector4( string data )
  619. {
  620. string[] parsedData = data.Split( VECTOR_SEPARATOR );
  621. if ( parsedData.Length >= 4 )
  622. {
  623. return new Vector4( Convert.ToSingle( parsedData[ 0 ] ),
  624. Convert.ToSingle( parsedData[ 1 ] ),
  625. Convert.ToSingle( parsedData[ 2 ] ),
  626. Convert.ToSingle( parsedData[ 3 ] ) );
  627. }
  628. return Vector4.zero;
  629. }
  630. public static Color StringToColor( string data )
  631. {
  632. string[] parsedData = data.Split( VECTOR_SEPARATOR );
  633. if ( parsedData.Length >= 4 )
  634. {
  635. return new Color( Convert.ToSingle( parsedData[ 0 ] ),
  636. Convert.ToSingle( parsedData[ 1 ] ),
  637. Convert.ToSingle( parsedData[ 2 ] ),
  638. Convert.ToSingle( parsedData[ 3 ] ) );
  639. }
  640. return Color.white;
  641. }
  642. public static Matrix4x4 StringToMatrix3x3( string data )
  643. {
  644. string[] parsedData = data.Split( VECTOR_SEPARATOR );
  645. if ( parsedData.Length == 9 )
  646. {
  647. Matrix4x4 matrix = new Matrix4x4();
  648. matrix[ 0, 0 ] = Convert.ToSingle( parsedData[ 0 ] );
  649. matrix[ 0, 1 ] = Convert.ToSingle( parsedData[ 1 ] );
  650. matrix[ 0, 2 ] = Convert.ToSingle( parsedData[ 2 ] );
  651. matrix[ 1, 0 ] = Convert.ToSingle( parsedData[ 3 ] );
  652. matrix[ 1, 1 ] = Convert.ToSingle( parsedData[ 4 ] );
  653. matrix[ 1, 2 ] = Convert.ToSingle( parsedData[ 5 ] );
  654. matrix[ 2, 0 ] = Convert.ToSingle( parsedData[ 6 ] );
  655. matrix[ 2, 1 ] = Convert.ToSingle( parsedData[ 7 ] );
  656. matrix[ 2, 2 ] = Convert.ToSingle( parsedData[ 8 ] );
  657. return matrix;
  658. }
  659. return Matrix4x4.identity;
  660. }
  661. public static Matrix4x4 StringToMatrix4x4( string data )
  662. {
  663. string[] parsedData = data.Split( VECTOR_SEPARATOR );
  664. if ( parsedData.Length == 16 )
  665. {
  666. Matrix4x4 matrix = new Matrix4x4();
  667. matrix[ 0, 0 ] = Convert.ToSingle( parsedData[ 0 ] );
  668. matrix[ 0, 1 ] = Convert.ToSingle( parsedData[ 1 ] );
  669. matrix[ 0, 2 ] = Convert.ToSingle( parsedData[ 2 ] );
  670. matrix[ 0, 3 ] = Convert.ToSingle( parsedData[ 3 ] );
  671. matrix[ 1, 0 ] = Convert.ToSingle( parsedData[ 4 ] );
  672. matrix[ 1, 1 ] = Convert.ToSingle( parsedData[ 5 ] );
  673. matrix[ 1, 2 ] = Convert.ToSingle( parsedData[ 6 ] );
  674. matrix[ 1, 3 ] = Convert.ToSingle( parsedData[ 7 ] );
  675. matrix[ 2, 0 ] = Convert.ToSingle( parsedData[ 8 ] );
  676. matrix[ 2, 1 ] = Convert.ToSingle( parsedData[ 9 ] );
  677. matrix[ 2, 2 ] = Convert.ToSingle( parsedData[ 10 ] );
  678. matrix[ 2, 3 ] = Convert.ToSingle( parsedData[ 11 ] );
  679. matrix[ 3, 0 ] = Convert.ToSingle( parsedData[ 12 ] );
  680. matrix[ 3, 1 ] = Convert.ToSingle( parsedData[ 13 ] );
  681. matrix[ 3, 2 ] = Convert.ToSingle( parsedData[ 14 ] );
  682. matrix[ 3, 3 ] = Convert.ToSingle( parsedData[ 15 ] );
  683. return matrix;
  684. }
  685. return Matrix4x4.identity;
  686. }
  687. public static void SaveTextureToDisk( Texture2D tex, string pathname )
  688. {
  689. byte[] rawData = tex.GetRawTextureData();
  690. Texture2D newTex = new Texture2D( tex.width, tex.height, tex.format, tex.mipmapCount > 1, false );
  691. newTex.LoadRawTextureData( rawData );
  692. newTex.Apply();
  693. byte[] pngData = newTex.EncodeToPNG();
  694. File.WriteAllBytes( pathname, pngData );
  695. }
  696. //public static void SaveObjToList( string newObj )
  697. //{
  698. // Debug.Log( UIUtils.CurrentWindow.Lastpath );
  699. // UIUtils.CurrentWindow.Lastpath = newObj;
  700. // string lastOpenedObj = EditorPrefs.GetString( IOUtils.LAST_OPENED_OBJ_ID );
  701. // string[] allLocations = lastOpenedObj.Split( ':' );
  702. // string lastLocation = allLocations[ allLocations.Length - 1 ];
  703. // string resave = string.Empty;
  704. // for ( int i = 0; i < allLocations.Length; i++ )
  705. // {
  706. // if ( string.IsNullOrEmpty( allLocations[ i ] ) )
  707. // continue;
  708. // resave += allLocations[ i ];
  709. // resave += ":";
  710. // }
  711. // resave += newObj;
  712. // EditorPrefs.SetString( IOUtils.LAST_OPENED_OBJ_ID, resave );
  713. //}
  714. //public static void DeleteObjFromList( string newObj )
  715. //{
  716. // string lastOpenedObj = EditorPrefs.GetString( IOUtils.LAST_OPENED_OBJ_ID );
  717. // string[] allLocations = lastOpenedObj.Split( ':' );
  718. // string resave = string.Empty;
  719. // for ( int i = 0; i < allLocations.Length; i++ )
  720. // {
  721. // if ( string.IsNullOrEmpty( allLocations[ i ] ) || newObj.Equals( allLocations[ i ] ) )
  722. // continue;
  723. // resave += allLocations[ i ];
  724. // if ( i < allLocations.Length - 1 )
  725. // resave += ":";
  726. // }
  727. // EditorPrefs.SetString( IOUtils.LAST_OPENED_OBJ_ID, resave );
  728. //}
  729. }
  730. }