├── .docfx ├── api │ ├── index.md │ └── .gitignore ├── toc.yml ├── index.md ├── .gitignore └── docfx.json ├── Runtime ├── Eunomia.asmdef ├── Eunomia.csproj.meta ├── StateMachine.md.meta ├── Eunomia.asmdef.meta ├── Random.meta ├── FileUtility.meta ├── Filters.meta ├── IEnumerableExtensions.meta ├── Arrays.cs.meta ├── Math.cs.meta ├── WordList.cs.meta ├── Dispatcher.cs.meta ├── IntExtensions.cs.meta ├── StateMachine.cs.meta ├── URLUtility.cs.meta ├── ArrayExtensions.cs.meta ├── FileUtility │ ├── Read.cs.meta │ ├── Write.cs.meta │ ├── ReadOrCreate.cs.meta │ ├── Write.cs │ ├── ReadOrCreate.cs │ └── Read.cs ├── FloatExtensions.cs.meta ├── ListExtensions.cs.meta ├── Random │ ├── IRandom.cs.meta │ ├── SystemRandomWrapper.cs.meta │ ├── IRandom.cs │ └── SystemRandomWrapper.cs ├── StringExtensions.cs.meta ├── Filters │ ├── KalmanFilterFloat.cs.meta │ └── KalmanFilterFloat.cs ├── IEnumerableExtensions │ ├── Random.cs.meta │ ├── Comparing.cs.meta │ ├── Duplicating.cs.meta │ ├── Filtering.cs.meta │ ├── ForEach.cs.meta │ ├── LinqNaming.cs.meta │ ├── OfStrings.cs.meta │ ├── Reducing.cs.meta │ ├── Searching.cs.meta │ ├── Filtering.cs │ ├── OfStrings.cs │ ├── Duplicating.cs │ ├── Reducing.cs │ ├── Comparing.cs │ ├── LinqNaming.cs │ ├── ForEach.cs │ ├── Searching.cs │ └── Random.cs ├── Eunomia.csproj ├── ArrayExtensions.cs ├── URLUtility.cs ├── Arrays.cs ├── StringExtensions.cs ├── Math.cs ├── ListExtensions.cs ├── Dispatcher.cs ├── WordList.cs ├── StateMachine.md ├── IntExtensions.cs ├── FloatExtensions.cs └── StateMachine.cs ├── .vscode ├── settings.json ├── launch.json └── tasks.json ├── Eunomia.sln.meta ├── README.md.meta ├── package.json.meta ├── Eunomia.sln.DotSettings.meta ├── Tests ├── EunomiaTests.csproj.meta ├── Eunomia.Tests.asmdef.meta ├── DispatcherTests.cs.meta ├── FloatExtensionsTests.cs.meta ├── IntExtensionsTests.cs.meta ├── StringExtensionsTests.cs.meta ├── Eunomia.Tests.asmdef ├── StringExtensionsTests.cs ├── EunomiaTests.csproj ├── IntExtensionsTests.cs ├── FloatExtensionsTests.cs └── DispatcherTests.cs ├── Runtime.meta ├── Tests.meta ├── .netconfig ├── README.md ├── .github └── workflows │ ├── build.yml │ ├── build_and_push_documentation.yml │ └── test_and_report_to_coveralls.yml ├── Eunomia.sln.DotSettings ├── package.json ├── Eunomia.sln ├── .gitignore └── LICENSE /.docfx/api/index.md: -------------------------------------------------------------------------------- 1 | # API Documentation 2 | -------------------------------------------------------------------------------- /Runtime/Eunomia.asmdef: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Eunomia" 3 | } 4 | -------------------------------------------------------------------------------- /.docfx/toc.yml: -------------------------------------------------------------------------------- 1 | - name: Api Documentation 2 | href: api/ 3 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.exclude": { 3 | "**/._*.*": true 4 | } 5 | } -------------------------------------------------------------------------------- /.docfx/api/.gitignore: -------------------------------------------------------------------------------- 1 | ############### 2 | # temp file # 3 | ############### 4 | *.yml 5 | .manifest 6 | -------------------------------------------------------------------------------- /.docfx/index.md: -------------------------------------------------------------------------------- 1 | # Eunomia C# 2 | 3 | Adorkable's go-to utilities for C#, named for the Greek goddess of green pastures, law and legislation 4 | -------------------------------------------------------------------------------- /.docfx/.gitignore: -------------------------------------------------------------------------------- 1 | ############### 2 | # folder # 3 | ############### 4 | /**/DROP/ 5 | /**/TEMP/ 6 | /**/packages/ 7 | /**/bin/ 8 | /**/obj/ 9 | _site 10 | -------------------------------------------------------------------------------- /Eunomia.sln.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 8d0ac6fe709844955b98cdb83671fef6 3 | DefaultImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /README.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 06cfa38570d3d4e709ecc11a02b93ee8 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /package.json.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 119edd0ffe7ca4ab9b4fee36c347b6d2 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Eunomia.sln.DotSettings.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: d47ba2e35442945e7bcc8a19102ad402 3 | DefaultImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Runtime/Eunomia.csproj.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 813319b6ab9e745c9acfffb7435d4f80 3 | DefaultImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Tests/EunomiaTests.csproj.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: c720db6fffe2942db85644da63f9b038 3 | DefaultImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Runtime.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 78925ecfe16454a6b875b2053c9bc5d6 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Runtime/StateMachine.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: bb6604d99897e4fef85177d207977a04 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Tests.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 79d1d2a35bc5a492086fff1e31dce1c3 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Runtime/Eunomia.asmdef.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: ad797131972064e7d9064b2ac6ba9b47 3 | AssemblyDefinitionImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Runtime/Random.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 27d00af05bc7e4d48aa6d04866978c97 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Runtime/FileUtility.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 314403f6df29b4e5e9840e20daf5baf0 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Runtime/Filters.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 221975af4df2d4ec7bd8f7d676198052 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Tests/Eunomia.Tests.asmdef.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: f15d68a8eb11340078d95a70ab065d91 3 | AssemblyDefinitionImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: cbc788d16cdec485c99eb127aba37e49 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Runtime/Arrays.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: b869bc352c09a48fca13fcb9a20af3af 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/Math.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 6adb1ed1570f0408bac0db3aedfa825f 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/WordList.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 7f9cbaafa49ce47da952cdde55469ee9 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/Dispatcher.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: e0786005169714297aba72ab1410c05e 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/IntExtensions.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: c29679587b22f45b1ae267a92acdae79 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/StateMachine.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 2f04d1f1d3512486da7e9e6502274a08 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/URLUtility.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: a21f5bca6002e4c1d911db4c8dc56621 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Tests/DispatcherTests.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: ed016dae410bc470f97ba5cdf1118ccd 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/ArrayExtensions.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 7f38d913a5eab494eaea0df804ff7161 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/FileUtility/Read.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 6b1fdf05535fa472188438d6c7b776e5 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/FileUtility/Write.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 27d6fb408074f4e80ba47e1453c986d0 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/FloatExtensions.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 423aa5ae8371d4ac8b1000fa89d5f9cd 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/ListExtensions.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: d25f73e5311e043efb30737e4d125e1e 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/Random/IRandom.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 4cae3db865c6f4ff68c8f9dda5c009d4 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/StringExtensions.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 1a7cea70eb6134ced90c8ca29ff54216 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Tests/FloatExtensionsTests.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: de15627001a2e4478bba0a1d30bb5512 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Tests/IntExtensionsTests.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: c5ce5531969bf475fb81bc2e0e41296f 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Tests/StringExtensionsTests.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: a0d6b460c609a43a7b046eae3f620541 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/FileUtility/ReadOrCreate.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: bc38fb7bdf46f4b70a9d4e5302f4b159 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/Filters/KalmanFilterFloat.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 3a25ec96a9d944708ad9408d96e87f9e 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/Random.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 9d1db649a8a114da9b61347769a17408 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/Random/SystemRandomWrapper.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 48300f0a1ee4441c88d4927dfa713211 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/Comparing.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 331194630bb044a2fb0d9f4f52b15861 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/Duplicating.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: b2ba89679bb76424a8118b96a0738787 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/Filtering.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: ed96702c06350457db453382ec203b19 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/ForEach.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: ed96702c06350457db453382ec203b18 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/LinqNaming.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 01e74a18d70d14ce0b94b32c78de5bba 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/OfStrings.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: e8a4b1ced1d934464a74c40c7f1b92f8 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/Reducing.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: ed96702c06350457db453382ec203b20 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/Searching.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: e2419bec430da45d781403ff1ac35bff 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /.netconfig: -------------------------------------------------------------------------------- 1 | [ReportGenerator] 2 | reports = "./TestResults/coverage.json" 3 | targetdir = "./TestResults/Coverage" 4 | reporttype = Html 5 | reporttype = HtmlChart 6 | reporttype = HtmlInline 7 | reporttype = HtmlSummary 8 | reporttype = MarkdownSummary 9 | reporttype = Badges 10 | reporttype = lcov 11 | reporttype = Xml -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Eunomia C# 2 | The team's go-to utilities for C#, named for the Greek goddess of green pastures, law and legislation 3 | 4 | [![Coverage Status](https://coveralls.io/repos/github/Adorkable/EunomiaCSharp/badge.svg?branch=master)](https://coveralls.io/github/Adorkable/EunomiaCSharp?branch=master) 5 | 6 | [Documentation](https://adorkable.github.io/EunomiaCSharp/) 7 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Setup .NET 13 | uses: actions/setup-dotnet@v1 14 | with: 15 | dotnet-version: 3.1.x 16 | - name: Restore dependencies 17 | run: dotnet restore 18 | - name: Build 19 | run: dotnet build --no-restore 20 | -------------------------------------------------------------------------------- /Eunomia.sln.DotSettings: -------------------------------------------------------------------------------- 1 | 2 | True 3 | True -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "com.adorkable.eunomia-csharp", 3 | "displayName": "Eunomia C#", 4 | "version": "1.7.3", 5 | "unity": "2019.2", 6 | "category": "Library/Utility", 7 | "keywords": [ 8 | "package", 9 | "unity" 10 | ], 11 | "description": "The team's go-to utilities for C#, named for the Greek goddess of green pastures, law and legislation", 12 | "main": "index.js", 13 | "scripts": { 14 | "test": "echo \"Error: no test specified\" && exit 1" 15 | }, 16 | "author": "Ian G ", 17 | "license": "ISC" 18 | } -------------------------------------------------------------------------------- /.github/workflows/build_and_push_documentation.yml: -------------------------------------------------------------------------------- 1 | # This is a basic workflow to help you get started with Actions 2 | 3 | name: Build and Push Documentation to Github Pages 4 | 5 | on: 6 | release: 7 | types: 8 | - published 9 | 10 | workflow_dispatch: 11 | 12 | jobs: 13 | build_and_push: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v2 17 | 18 | - name: Build 19 | uses: nikeee/docfx-action@v1.0.0 20 | with: 21 | args: ./.docfx/docfx.json 22 | 23 | - name: Push 24 | uses: peaceiris/actions-gh-pages@v3 25 | with: 26 | github_token: ${{ secrets.GITHUB_TOKEN }} 27 | publish_dir: ./.docfx/_site 28 | -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/Filtering.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | // ReSharper disable once CheckNamespace - In folder for organization reasons 5 | namespace Eunomia 6 | { 7 | // ReSharper disable once InconsistentNaming - extensions for IEnumerable :P 8 | public static partial class IEnumerableExtensions 9 | { 10 | // TODO: do for nullables 11 | public static bool NotNullTest(T test) where T : class 12 | { 13 | return test != null; 14 | } 15 | 16 | public static IEnumerable OnlyNonNull(this IEnumerable objects) where T : class 17 | { 18 | return objects.Filter(NotNullTest); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/OfStrings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | // ReSharper disable once CheckNamespace 5 | namespace Eunomia 6 | { 7 | // ReSharper disable once InconsistentNaming - extensions for IEnumerable :P 8 | public static partial class IEnumerableExtensions 9 | { 10 | public static IEnumerable FilterNullOrEmpty(this IEnumerable enumerableToFilter) 11 | { 12 | return enumerableToFilter.FilterNot(String.IsNullOrEmpty); 13 | } 14 | 15 | public static IEnumerable FilterIsNullOrWhiteSpace(this IEnumerable enumerableToFilter) 16 | { 17 | return enumerableToFilter.FilterNot(String.IsNullOrWhiteSpace); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Tests/Eunomia.Tests.asmdef: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Eunomia.Tests", 3 | "references": [], 4 | "includePlatforms": [ 5 | ], 6 | "excludePlatforms": [ 7 | "Android", 8 | "CloudRendering", 9 | "Editor", 10 | "iOS", 11 | "LinuxStandalone64", 12 | "Lumin", 13 | "macOSStandalone", 14 | "PS4", 15 | "Stadia", 16 | "Switch", 17 | "tvOS", 18 | "WSA", 19 | "WebGL", 20 | "WindowsStandalone32", 21 | "WindowsStandalone64", 22 | "XboxOne"], 23 | "allowUnsafeCode": false, 24 | "overrideReferences": false, 25 | "precompiledReferences": [], 26 | "autoReferenced": true, 27 | "defineConstraints": [], 28 | "versionDefines": [], 29 | "noEngineReferences": false 30 | } -------------------------------------------------------------------------------- /Tests/StringExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | 3 | // ReSharper disable once CheckNamespace 4 | namespace Eunomia.Tests 5 | { 6 | [TestClass()] 7 | public class StringExtensionsTests 8 | { 9 | [TestMethod()] 10 | public void RemoveXmlTagsTest() 11 | { 12 | const string inside = "lalalal"; 13 | var testWith = $"{inside}"; 14 | Assert.AreEqual(inside, testWith.RemoveXmlTags()); 15 | 16 | Assert.AreEqual(inside, inside.RemoveXmlTags()); 17 | 18 | string testNull = null; 19 | Assert.AreEqual(null, StringExtensions.RemoveXmlTags(testNull)); 20 | 21 | var spaces = " "; 22 | Assert.AreEqual(spaces, spaces.RemoveXmlTags()); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Runtime/FileUtility/Write.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Text; 3 | using System.Threading.Tasks; 4 | 5 | // ReSharper disable once CheckNamespace - In folder for organization reasons 6 | namespace Eunomia 7 | { 8 | public static partial class FileUtility 9 | { 10 | public static async Task WriteFile(string fileName, string contents) 11 | { 12 | // ReSharper disable once UseAwaitUsing - Not supported by Unity 2019 13 | using (var stream = File.Open(fileName, FileMode.Create)) 14 | { 15 | var buffer = Encoding.UTF8.GetBytes(contents); 16 | #pragma warning disable CA1835 // Not supported by Unity 2019 17 | await stream.WriteAsync(buffer, 0, buffer.Length); 18 | #pragma warning restore CA1835 19 | stream.Close(); 20 | } 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Runtime/Eunomia.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 1.4.2 6 | Ian G <yo.ian.g@gmail.com> 7 | Adorkable LLC 8 | Eunomia CSharp 9 | The team's go-to utilities for C#, named for the Greek goddess of green pastures, law and legislation 10 | 11 | https://github.com/Adorkable/eunomiacsharp 12 | https://github.com/Adorkable/eunomiacsharp 13 | Git 14 | csharp, utility, library, eunomia 15 | true 16 | 17 | 18 | -------------------------------------------------------------------------------- /Runtime/ArrayExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Eunomia 4 | { 5 | public static class ArrayExtensions 6 | { 7 | public static bool EqualContents(this T[] array, T[] compareTo) where T : IEquatable 8 | { 9 | if (array == null && compareTo == null) 10 | { 11 | return true; 12 | } 13 | 14 | if (array == null || compareTo == null) 15 | { 16 | return false; 17 | } 18 | 19 | if (array.Length != compareTo.Length) 20 | { 21 | return false; 22 | } 23 | 24 | for (var index = 0; index < array.Length; index++) 25 | { 26 | if (array[index].Equals(compareTo[index]) == false) 27 | { 28 | return false; 29 | } 30 | } 31 | 32 | return true; 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/Duplicating.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | // ReSharper disable once CheckNamespace - In folder for organization reasons 6 | namespace Eunomia 7 | { 8 | // ReSharper disable once InconsistentNaming - extensions for IEnumerable :P 9 | public static partial class IEnumerableExtensions 10 | { 11 | // TODO: do we have to do ToList to actually create a copy? What is the fastest method 12 | public static IList Clone(this IEnumerable listToClone) where T : ICloneable 13 | { 14 | return listToClone.Select(item => (T) item.Clone()).ToList(); 15 | } 16 | 17 | // TODO: do we have to do ToList to actually create a copy? What is the fastest method 18 | public static IList Copy(this IEnumerable listToCopy) 19 | { 20 | return listToCopy.Select(item => item).ToList(); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /.github/workflows/test_and_report_to_coveralls.yml: -------------------------------------------------------------------------------- 1 | name: Test and Report to Coveralls 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Setup .NET 13 | uses: actions/setup-dotnet@v1 14 | with: 15 | dotnet-version: 3.1.x 16 | - name: Restore dependencies 17 | run: dotnet restore 18 | - name: Run Tests 19 | run: dotnet test --verbosity normal /p:CollectCoverage=true /p:CoverletOutputFormat=lcov /p:CoverletOutput=../TestResults/lcov.info 20 | 21 | - name: Coveralls GitHub Action 22 | # You may pin to the exact commit or the version. 23 | # uses: coverallsapp/github-action@9ba913c152ae4be1327bfb9085dc806cedb44057 24 | uses: coverallsapp/github-action@1.1.3 25 | with: 26 | # 27 | github-token: ${{ secrets.GITHUB_TOKEN }} 28 | # Path to lcov file 29 | path-to-lcov: ./TestResults/lcov.info 30 | -------------------------------------------------------------------------------- /Tests/EunomiaTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | false 7 | 8 | 9 | 10 | 11 | runtime; build; native; contentfiles; analyzers; buildtransitive 12 | all 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Runtime/URLUtility.cs: -------------------------------------------------------------------------------- 1 | namespace Eunomia 2 | { 3 | public class UrlUtility 4 | { 5 | public enum Protocol 6 | { 7 | Http, 8 | WebSocket 9 | } 10 | 11 | public static string ProtocolPrefix(Protocol protocol, bool secure) 12 | { 13 | switch (protocol) 14 | { 15 | case Protocol.Http: 16 | return secure 17 | ? "https" 18 | : "http"; 19 | 20 | case Protocol.WebSocket: 21 | return secure 22 | ? "wss" 23 | : "ws"; 24 | } 25 | 26 | return ""; 27 | } 28 | 29 | public static string ComposeUrl(Protocol protocol, bool secure, string host, int port) 30 | { 31 | var result = ProtocolPrefix(protocol, secure) + "://" + host; 32 | 33 | // Make this removal optional 34 | if (port != 80) 35 | { 36 | result += ":" + port; 37 | } 38 | 39 | return result; 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /Runtime/Arrays.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Eunomia 4 | { 5 | public class Arrays 6 | { 7 | /// 8 | /// Create a new array with an element added to the end 9 | /// 10 | /// Element to add 11 | /// Array which will be copied and whose copy will be added to 12 | /// New array with `add` param added to the end 13 | public static T[] AddToBack(T add, T[] to) 14 | { 15 | var result = to; 16 | 17 | AddToBack(add, ref result); 18 | 19 | return result; 20 | } 21 | 22 | /// 23 | /// Resizes array `to` and adds element to the end 24 | /// 25 | /// Element to add 26 | /// Array that will be resized and added to 27 | public static void AddToBack(T add, ref T[] to) 28 | { 29 | var index = to.Length; 30 | 31 | Array.Resize(ref to, to.Length + 1); 32 | 33 | to[index] = add; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Runtime/StringExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Text.RegularExpressions; 4 | 5 | namespace Eunomia 6 | { 7 | public static class StringExtensions 8 | { 9 | // TODO: add support for and other characters within "..." 10 | public static readonly Lazy XmlTag = new Lazy( 11 | () => new Regex(@"([<][/]?[a-zA-Z="" ]*[>])", RegexOptions.Compiled | RegexOptions.IgnoreCase) 12 | ); 13 | 14 | public static string RemoveXmlTags(this string clean) 15 | { 16 | if (clean == null) 17 | { 18 | return null; 19 | } 20 | 21 | var matches = XmlTag.Value.Matches(clean); 22 | 23 | var result = clean; 24 | for (var index = matches.Count - 1; index >= 0; index--) 25 | { 26 | var match = matches[index]; 27 | var start = match.Groups[0].Index; 28 | var matchedString = match.Groups[0].Value; 29 | result = result.Remove(start, matchedString.Count()); 30 | } 31 | 32 | return result; 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | // Use IntelliSense to find out which attributes exist for C# debugging 6 | // Use hover for the description of the existing attributes 7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/Tests/bin/Debug/netcoreapp3.1/EunomiaTests.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}/Tests", 16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console 17 | "console": "internalConsole", 18 | "stopAtEntry": false 19 | }, 20 | { 21 | "name": ".NET Core Attach", 22 | "type": "coreclr", 23 | "request": "attach" 24 | } 25 | ] 26 | } -------------------------------------------------------------------------------- /Runtime/FileUtility/ReadOrCreate.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Threading.Tasks; 3 | 4 | // ReSharper disable once CheckNamespace - In folder for organization reasons 5 | namespace Eunomia 6 | { 7 | public static partial class FileUtility 8 | { 9 | /// 10 | /// Attempts to read a file which if not found is then created with `defaultContents` 11 | /// 12 | /// Name of file to read 13 | /// String contents to use to create file if it does not exist 14 | /// Contents of file, whether read or used to create file from `defaultContents` 15 | public static async Task ReadFileOrCreateDefault(string fileName, string defaultContents) 16 | { 17 | try 18 | { 19 | var contents = await ReadFile(fileName); 20 | return contents; 21 | } 22 | catch (FileNotFoundException) 23 | { 24 | await WriteFile(fileName, defaultContents); 25 | return defaultContents; 26 | } 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/Reducing.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | // ReSharper disable once CheckNamespace - In folder for organization reasons 5 | namespace Eunomia 6 | { 7 | // ReSharper disable once InconsistentNaming - extensions for IEnumerable :P 8 | public static partial class IEnumerableExtensions 9 | { 10 | // TODO: do for nullables 11 | public static readonly Func NullCountReducer = (previous, test) => 12 | { 13 | var testedCount = test == null ? 1 : 0; 14 | return previous + testedCount; 15 | }; 16 | 17 | public static int NullCount(this IEnumerable objects) 18 | { 19 | return objects.Reduce(NullCountReducer, 0); 20 | } 21 | 22 | public static readonly Func NotNullCountReducer = (previous, test) => 23 | { 24 | var testedCount = test != null ? 1 : 0; 25 | return previous + testedCount; 26 | }; 27 | 28 | public static int NotNullCount(this IEnumerable objects) 29 | { 30 | return objects.Reduce(NotNullCountReducer, 0); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/Comparing.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | // ReSharper disable once CheckNamespace - In folder for organization reasons 5 | namespace Eunomia 6 | { 7 | // ReSharper disable once InconsistentNaming - extensions for IEnumerable :P 8 | public static partial class IEnumerableExtensions 9 | { 10 | public static bool EqualContents(this IEnumerable[] array, IEnumerable[] compareTo) 11 | where T : IEquatable 12 | { 13 | if (array == null && compareTo == null) 14 | { 15 | return true; 16 | } 17 | 18 | if (array == null || compareTo == null) 19 | { 20 | return false; 21 | } 22 | 23 | if (array.Length != compareTo.Length) 24 | { 25 | return false; 26 | } 27 | 28 | for (var index = 0; index < array.Length; index++) 29 | { 30 | if (array[index].Equals(compareTo[index]) == false) 31 | { 32 | return false; 33 | } 34 | } 35 | 36 | return true; 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /.docfx/docfx.json: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": [ 3 | { 4 | "src": [ 5 | { 6 | "src": "../", 7 | "files": [ 8 | "Runtime/Eunomia.csproj" 9 | ] 10 | } 11 | ], 12 | "dest": "api", 13 | "disableGitFeatures": false, 14 | "disableDefaultFilter": false 15 | } 16 | ], 17 | "build": { 18 | "content": [ 19 | { 20 | "files": [ 21 | "api/**.yml", 22 | "api/index.md" 23 | ] 24 | }, 25 | { 26 | "files": [ 27 | "toc.yml", 28 | "index.md" 29 | ] 30 | } 31 | ], 32 | "overwrite": [ 33 | { 34 | "exclude": [ 35 | "obj/**", 36 | "_site/**" 37 | ] 38 | } 39 | ], 40 | "dest": "_site", 41 | "globalMetadataFiles": [], 42 | "fileMetadataFiles": [], 43 | "template": [ 44 | "default" 45 | ], 46 | "postProcessors": [], 47 | "markdownEngineName": "markdig", 48 | "noLangKeyword": false, 49 | "keepFileLink": false, 50 | "cleanupCacheHistory": false, 51 | "disableGitFeatures": false, 52 | "sitemap": { 53 | "baseUrl": "https://adorkable.github.io/EunomiaCSharp", 54 | "priority": 0.1, 55 | "changeFreq": "weekly" 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /Runtime/Math.cs: -------------------------------------------------------------------------------- 1 | using System.Numerics; 2 | 3 | namespace Eunomia 4 | { 5 | public static class Math 6 | { 7 | public static (float, float) FitWithAspect((float, float) content, (float, float) match) 8 | { 9 | var ratio = content.Item1 / content.Item2; 10 | var ratioMatch = match.Item1 / match.Item2; 11 | 12 | float newWidth, newHeight; 13 | if (ratioMatch > ratio) 14 | { 15 | newWidth = content.Item1 * match.Item2 / content.Item2; 16 | newHeight = match.Item2; 17 | } 18 | else 19 | { 20 | newWidth = match.Item1; 21 | newHeight = content.Item2 * match.Item1 / content.Item1; 22 | } 23 | 24 | return (newWidth, newHeight); 25 | } 26 | 27 | public static Vector2 FitWithAspect(Vector2 content, Vector2 match) 28 | { 29 | var ratio = content.X / content.Y; 30 | var ratioMatch = match.X / match.Y; 31 | 32 | float newWidth, newHeight; 33 | if (ratioMatch > ratio) 34 | { 35 | newWidth = content.X * match.Y / content.Y; 36 | newHeight = match.Y; 37 | } 38 | else 39 | { 40 | newWidth = match.X; 41 | newHeight = content.Y * match.X / content.Y; 42 | } 43 | 44 | return new Vector2(newWidth, newHeight); 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /Tests/IntExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | 4 | // ReSharper disable once CheckNamespace 5 | namespace Eunomia.Tests 6 | { 7 | [TestClass()] 8 | public class IntExtensionsTests 9 | { 10 | [TestMethod()] 11 | public void WrapTest() 12 | { 13 | var seven = 7; 14 | 15 | Assert.AreEqual(1, seven.Wrap(3)); 16 | 17 | Assert.AreEqual(0, seven.Wrap(7)); 18 | Assert.AreEqual(7, seven.Wrap(10)); 19 | 20 | Assert.AreEqual(2, (-3).Wrap(5)); 21 | 22 | Assert.ThrowsException(() => seven.Wrap(0)); 23 | 24 | Assert.ThrowsException(() => 5.Wrap(-2)); 25 | } 26 | 27 | [TestMethod()] 28 | public void ClampTest() 29 | { 30 | Assert.AreEqual(5, 10.Clamp(0, 5)); 31 | Assert.AreEqual(4, 4.Clamp(0, 5)); 32 | Assert.AreEqual(0, (-1).Clamp(0, 5)); 33 | Assert.AreEqual(0, 10.Clamp(0, 0)); 34 | 35 | Assert.ThrowsException(() => 10.Clamp(0, -10)); 36 | 37 | // Assert.Fail("Different lower bounds"); 38 | } 39 | 40 | [TestMethod()] 41 | public void ClampUpperExclusiveTest() 42 | { 43 | Assert.AreEqual(4, 10.ClampUpperExclusive(5)); 44 | Assert.AreEqual(4, 4.ClampUpperExclusive(5)); 45 | Assert.AreEqual(0, (-1).ClampUpperExclusive(5)); 46 | 47 | Assert.ThrowsException(() => 10.ClampUpperExclusive(0)); 48 | Assert.ThrowsException(() => 10.ClampUpperExclusive(-10)); 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /Runtime/ListExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Eunomia 5 | { 6 | public static class ListExtensions 7 | { 8 | public static void ForEach(this IList listToForEach, Action action) 9 | { 10 | foreach (var element in listToForEach) 11 | { 12 | action(element); 13 | } 14 | } 15 | 16 | public static IEnumerable RemoveAll(this IList listToRemoveFrom, IList remove) where T : ICloneable 17 | { 18 | var result = listToRemoveFrom.Clone(); 19 | remove.ForEach(value => { listToRemoveFrom.Remove(value); }); 20 | return result; 21 | } 22 | 23 | /// 24 | /// Randomizes contents of list based on Fisher-Yates shuffle 25 | /// Based on: https://stackoverflow.com/a/1262619 26 | /// 27 | /// 28 | /// List to randomize 29 | /// A reference to the original list, now randomized 30 | public static IList Randomize(this IList listToRandomize, IRandom random = null) 31 | { 32 | var useRandom = random ?? IEnumerableExtensions.GetFallbackRandom(); 33 | 34 | int length = listToRandomize.Count; 35 | while (length > 1) 36 | { 37 | length--; 38 | int k = useRandom.Next(length + 1); 39 | var value = listToRandomize[k]; 40 | listToRandomize[k] = listToRandomize[length]; 41 | listToRandomize[length] = value; 42 | } 43 | return listToRandomize; 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/LinqNaming.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | // ReSharper disable once CheckNamespace - In folder for organization reasons 6 | namespace Eunomia 7 | { 8 | // ReSharper disable once InconsistentNaming - extensions for IEnumerable :P 9 | public static partial class IEnumerableExtensions 10 | { 11 | public static IEnumerable Filter(this IEnumerable enumerableToFilter, Func predicate) 12 | { 13 | return enumerableToFilter.Where(predicate); 14 | } 15 | 16 | public static IEnumerable FilterNot(this IEnumerable enumerableToFilter, Func predicate) 17 | { 18 | return enumerableToFilter.Where((element, index) => !predicate(element, index)); 19 | } 20 | 21 | public static TReduced Reduce(this IEnumerable enumerableToReduce, 22 | Func reduce, TReduced start) 23 | { 24 | return enumerableToReduce.Aggregate(start, reduce); 25 | } 26 | 27 | public static IEnumerable Map(this IEnumerable enumerableToMap, Func selector) 28 | { 29 | return enumerableToMap.Select(selector); 30 | } 31 | 32 | public static IEnumerable FlatMap(this IEnumerable> enumerableToFlatten) 33 | { 34 | return enumerableToFlatten.SelectMany(value => value); 35 | } 36 | 37 | public static void ForEach(this IEnumerable enumerableToOperateOn, Action operation) 38 | { 39 | foreach (var operateOn in enumerableToOperateOn) 40 | { 41 | operation(operateOn); 42 | } 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /Tests/FloatExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | 4 | // ReSharper disable once CheckNamespace 5 | namespace Eunomia.Tests 6 | { 7 | [TestClass()] 8 | public class FloatExtensionsTests 9 | { 10 | [TestMethod()] 11 | public void WrapTest() 12 | { 13 | float seven = 7; 14 | 15 | Assert.AreEqual(1.0f, seven.Wrap(3.0f)); 16 | 17 | Assert.AreEqual(0.0f, seven.Wrap(7.0f)); 18 | Assert.AreEqual(7.0f, seven.Wrap(10.0f)); 19 | 20 | Assert.AreEqual(2.0f, (-3.0f).Wrap(5.0f)); 21 | 22 | Assert.ThrowsException(() => seven.Wrap(0.0f)); 23 | 24 | Assert.ThrowsException(() => 5.0f.Wrap(-2.0f)); 25 | } 26 | 27 | [TestMethod()] 28 | public void ClampTest() 29 | { 30 | Assert.AreEqual(5, 10.0f.Clamp(0, 5.0f)); 31 | Assert.AreEqual(4, 4.0f.Clamp(0, 5.0f)); 32 | Assert.AreEqual(0, (-1.0f).Clamp(0, 5.0f)); 33 | Assert.AreEqual(0, 10.0f.Clamp(0, 0)); 34 | 35 | Assert.ThrowsException(() => 10.0f.Clamp(0, -10)); 36 | 37 | // Assert.Fail("Different lower bounds"); 38 | } 39 | 40 | [TestMethod()] 41 | public void ClampUpperExclusiveTest() 42 | { 43 | Assert.AreEqual(4, 10.0f.ClampUpperExclusive(5)); 44 | Assert.AreEqual(4, 4.0f.ClampUpperExclusive(5)); 45 | Assert.AreEqual(0, (-1.0f).ClampUpperExclusive(5)); 46 | 47 | Assert.ThrowsException(() => 10.0f.ClampUpperExclusive(0)); 48 | Assert.ThrowsException(() => 10.0f.ClampUpperExclusive(-10)); 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /Runtime/Dispatcher.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Eunomia 5 | { 6 | // Based on: https://www.lucidumstudio.com/home/2017/12/5/lucidum-studio-async-code-execution-in-unity 7 | 8 | /// 9 | /// Utility class for ensuring a set of Actions are Invoked in order from a particular thread 10 | /// 11 | public class Dispatcher 12 | { 13 | private readonly List pending = new List(); 14 | 15 | public Action logUnhandledExceptions = null; 16 | private volatile bool pendingActions; 17 | 18 | public void Invoke(Action fn) 19 | { 20 | lock (pending) 21 | { 22 | pending.Add(fn); 23 | pendingActions = true; 24 | } 25 | } 26 | 27 | public void InvokePending() 28 | { 29 | if (!pendingActions) 30 | { 31 | return; 32 | } 33 | 34 | IEnumerable invoking; 35 | lock (pending) 36 | { 37 | if (pending.Count == 0) 38 | { 39 | return; 40 | } 41 | 42 | invoking = pending.Copy(); 43 | 44 | pending.Clear(); 45 | pendingActions = false; 46 | } 47 | 48 | invoking.ForEach((action) => 49 | { 50 | try 51 | { 52 | action.Invoke(); 53 | } 54 | catch (Exception exception) 55 | { 56 | if (logUnhandledExceptions != null) 57 | { 58 | logUnhandledExceptions.Invoke(exception); 59 | } 60 | // TODO: else collect and throw all exceptions 61 | } 62 | }); 63 | } 64 | }; 65 | }; -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/ForEach.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | // ReSharper disable once CheckNamespace - In folder for organization reasons 5 | namespace Eunomia 6 | { 7 | // ReSharper disable once InconsistentNaming - extensions for IEnumerable :P 8 | public static partial class IEnumerableExtensions 9 | { 10 | public static void ForEach(this IEnumerable enumerableToOperateOn, Action operation) 11 | { 12 | var index = 0; 13 | foreach (var operateOn in enumerableToOperateOn) 14 | { 15 | operation(operateOn, index); 16 | index += 1; 17 | } 18 | } 19 | 20 | /// 21 | /// 22 | /// 23 | /// Return `false` to continue iteration, `true` to stop 24 | public static void ForEach(this IEnumerable enumerableToOperateOn, Func operation) 25 | { 26 | foreach (var operateOn in enumerableToOperateOn) 27 | { 28 | if (operation(operateOn)) 29 | { 30 | return; 31 | } 32 | } 33 | } 34 | 35 | /// 36 | /// 37 | /// 38 | /// Return `false` to continue iteration, `true` to stop 39 | public static void ForEach(this IEnumerable enumerableToOperateOn, Func operation) 40 | { 41 | var index = 0; 42 | foreach (var operateOn in enumerableToOperateOn) 43 | { 44 | if (operation(operateOn, index)) 45 | { 46 | return; 47 | } 48 | 49 | index += 1; 50 | } 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /Runtime/WordList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Eunomia 5 | { 6 | [Serializable] 7 | public struct WordList 8 | { 9 | public IEnumerable All; 10 | public List> ByLength; 11 | 12 | public List WithLength(int length) 13 | { 14 | // TODO: or should we have a list of a 0 length string :P 15 | var lengthStartingWith1 = length - 1; 16 | return lengthStartingWith1 < ByLength.Count 17 | ? this.ByLength[lengthStartingWith1] 18 | : null; 19 | } 20 | 21 | public WordList(IEnumerable allWords) 22 | { 23 | this.All = allWords.FilterNullOrEmpty(); 24 | this.ByLength = ProcessWordsByLength(this.All); 25 | } 26 | 27 | /// Processing 28 | private static List> ProcessWordsByLength(IEnumerable all) 29 | { 30 | var processValues = new List(all.Clone()); 31 | var result = new List>(); 32 | 33 | var length = 1; 34 | var maxLength = processValues.Reduce( 35 | (previous, current) => System.Math.Max(previous, current.Length), 0 36 | ); 37 | 38 | while (processValues.Count > 0 && length <= maxLength) 39 | { 40 | var found = processValues.FindAll( 41 | // ReSharper disable once SimplifyConditionalTernaryExpression 42 | (test) => test != null 43 | ? test.Length == length 44 | : false 45 | ); 46 | 47 | // TODO: specify index to match Length - 1 purposefully to be safe 48 | result.Add(found); 49 | processValues.RemoveAll(found); 50 | length++; 51 | } 52 | 53 | return result; 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /Eunomia.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31729.503 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Eunomia", "Runtime\Eunomia.csproj", "{1FE20FF7-A626-49E9-A4D2-F817EE6E51C9}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EunomiaTests", "Tests\EunomiaTests.csproj", "{CB2A6693-672D-4DBE-B19E-B9F870CFD0AF}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {1FE20FF7-A626-49E9-A4D2-F817EE6E51C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {1FE20FF7-A626-49E9-A4D2-F817EE6E51C9}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {1FE20FF7-A626-49E9-A4D2-F817EE6E51C9}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {1FE20FF7-A626-49E9-A4D2-F817EE6E51C9}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {84A9F09A-2359-49B8-BC50-8DF2BFFB323D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {84A9F09A-2359-49B8-BC50-8DF2BFFB323D}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {84A9F09A-2359-49B8-BC50-8DF2BFFB323D}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {84A9F09A-2359-49B8-BC50-8DF2BFFB323D}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {CB2A6693-672D-4DBE-B19E-B9F870CFD0AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {CB2A6693-672D-4DBE-B19E-B9F870CFD0AF}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {CB2A6693-672D-4DBE-B19E-B9F870CFD0AF}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {CB2A6693-672D-4DBE-B19E-B9F870CFD0AF}.Release|Any CPU.Build.0 = Release|Any CPU 28 | EndGlobalSection 29 | GlobalSection(SolutionProperties) = preSolution 30 | HideSolutionNode = FALSE 31 | EndGlobalSection 32 | GlobalSection(ExtensibilityGlobals) = postSolution 33 | SolutionGuid = {581F9997-ABA4-474A-AD89-783AD738860E} 34 | EndGlobalSection 35 | EndGlobal 36 | -------------------------------------------------------------------------------- /Runtime/Random/IRandom.cs: -------------------------------------------------------------------------------- 1 | // ReSharper disable once CheckNamespace 2 | 3 | namespace Eunomia 4 | { 5 | public interface IRandom 6 | { 7 | /// 8 | /// Returns a non-negative random integer. 9 | /// 10 | /// A 32-bit signed integer that is greater than or equal to 0 and less than int.MaxValue. 11 | int Next(); 12 | 13 | /// 14 | /// Returns a non-negative random integer that is less than the specified maximum. 15 | /// 16 | /// 17 | /// The exclusive upper bound of the random number to be generated. `maxValue` must be greater than 18 | /// or equal to 0. 19 | /// 20 | /// 21 | /// A 32-bit signed integer that is greater than or equal to 0, and less than `maxValue`; that is, the range of 22 | /// return values ordinarily includes 0 but not `maxValue`. However, if `maxValue` equals 0, maxValue is returned. 23 | /// 24 | int Next(int maxValue); 25 | 26 | /// 27 | /// Returns a random integer that is within a specified range. 28 | /// 29 | /// The inclusive lower bound of the random number returned. 30 | /// 31 | /// The exclusive upper bound of the random number returned. `maxValue` must be greater than or 32 | /// equal to `minValue`. 33 | /// 34 | /// 35 | /// A signed integer greater than or equal to `minValue` and less than `maxValue`; that is, the range of return 36 | /// values includes `minValue` but not `maxValue`. If `minValue` equals `maxValue`, `minValue` is returned. 37 | /// 38 | /// `minValue` is greater than `maxValue`. 39 | int Next(int minValue, int maxValue); 40 | } 41 | } -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/Searching.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | // ReSharper disable once CheckNamespace 5 | namespace Eunomia 6 | { 7 | // ReSharper disable once InconsistentNaming - extensions for IEnumerable :P 8 | public static partial class IEnumerableExtensions 9 | { 10 | /// 11 | /// 12 | /// Found matcing item or default() and whether a match was found 13 | /// 14 | /// Return `true` to return the current item, return `false` to continue 15 | public static Found Find(this IEnumerable enumerableToOperateOn, Func operation) 16 | { 17 | var index = 0; 18 | foreach (var operateOn in enumerableToOperateOn) 19 | { 20 | if (operation(operateOn, index)) 21 | { 22 | return new Found() 23 | { 24 | index = index, 25 | result = operateOn, 26 | found = true 27 | }; 28 | } 29 | 30 | index += 1; 31 | } 32 | 33 | return new Found() {result = default, found = false}; 34 | } 35 | 36 | public static IEnumerable Filter(this IEnumerable enumerableToFilter, Func predicate) 37 | { 38 | return enumerableToFilter.Filter((element, index) => { return predicate(element); }); 39 | } 40 | 41 | public static IEnumerable FilterNot(this IEnumerable enumerableToFilter, Func predicate) 42 | { 43 | return enumerableToFilter.FilterNot((element, index) => { return predicate(element); }); 44 | } 45 | 46 | public struct Found 47 | { 48 | public int index; 49 | public T result; 50 | public bool found; 51 | }; 52 | } 53 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/Runtime/Eunomia.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile", 15 | "isBuildCommand": true 16 | }, 17 | { 18 | "label": "publish", 19 | "command": "dotnet", 20 | "type": "process", 21 | "args": [ 22 | "publish", 23 | "${workspaceFolder}/Runtime/Eunomia.csproj", 24 | "/property:GenerateFullPaths=true", 25 | "/consoleloggerparameters:NoSummary" 26 | ], 27 | "problemMatcher": "$msCompile" 28 | }, 29 | { 30 | "label": "watch", 31 | "command": "dotnet", 32 | "type": "process", 33 | "args": [ 34 | "watch", 35 | "run", 36 | "${workspaceFolder}/Runtime/Eunomia.csproj", 37 | "/property:GenerateFullPaths=true", 38 | "/consoleloggerparameters:NoSummary" 39 | ], 40 | "problemMatcher": "$msCompile" 41 | }, 42 | { 43 | "label": "test", 44 | "command": "dotnet", 45 | "type": "process", 46 | "args": [ 47 | "test", 48 | "${workspaceFolder}/Tests/EunomiaTests.csproj", 49 | "/property:GenerateFullPaths=true", 50 | "/consoleloggerparameters:NoSummary", 51 | "/p:CollectCoverage=true", 52 | "/p:CoverletOutput=${workspaceFolder}/TestResults/coverage.json" 53 | ], 54 | "problemMatcher": "$msCompile", 55 | "isTestCommand": true 56 | }, 57 | { 58 | "label": "generate_test_coverage_report", 59 | "command": "Tools/reportgenerator", 60 | "type": "process", 61 | "args": [ 62 | ], 63 | "problemMatcher": "$msCompile", 64 | } 65 | ] 66 | } -------------------------------------------------------------------------------- /Runtime/Random/SystemRandomWrapper.cs: -------------------------------------------------------------------------------- 1 | // ReSharper disable once CheckNamespace 2 | 3 | using System; 4 | 5 | namespace Eunomia 6 | { 7 | public class SystemRandomWrapper : IRandom 8 | { 9 | protected readonly Random random; 10 | 11 | /// 12 | /// Instantiates a new `SystemRandomWrapper` instance wrapping a `System.Random`. 13 | /// 14 | /// System.Random instance to wrap 15 | public SystemRandomWrapper(Random random) 16 | { 17 | this.random = random; 18 | } 19 | 20 | /// 21 | /// Returns a non-negative random integer. 22 | /// 23 | /// A 32-bit signed integer that is greater than or equal to 0 and less than int.MaxValue. 24 | int IRandom.Next() 25 | { 26 | return random.Next(); 27 | } 28 | 29 | /// 30 | /// Returns a non-negative random integer that is less than the specified maximum. 31 | /// 32 | /// 33 | /// The exclusive upper bound of the random number to be generated. `maxValue` must be greater than 34 | /// or equal to 0. 35 | /// 36 | /// 37 | /// A 32-bit signed integer that is greater than or equal to 0, and less than `maxValue`; that is, the range of 38 | /// return values ordinarily includes 0 but not `maxValue`. However, if `maxValue` equals 0, maxValue is returned. 39 | /// 40 | int IRandom.Next(int maxValue) 41 | { 42 | return random.Next(maxValue); 43 | } 44 | 45 | /// 46 | /// Returns a random integer that is within a specified range. 47 | /// 48 | /// The inclusive lower bound of the random number returned. 49 | /// 50 | /// The exclusive upper bound of the random number returned. `maxValue` must be greater than or 51 | /// equal to `minValue`. 52 | /// 53 | /// 54 | /// A signed integer greater than or equal to `minValue` and less than `maxValue`; that is, the range of return 55 | /// values includes `minValue` but not `maxValue`. If `minValue` equals `maxValue`, `minValue` is returned. 56 | /// 57 | /// `minValue` is greater than `maxValue`. 58 | int IRandom.Next(int minValue, int maxValue) 59 | { 60 | return random.Next(minValue, maxValue); 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /Runtime/IEnumerableExtensions/Random.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | // ReSharper disable once CheckNamespace - In folder for organization reasons 6 | namespace Eunomia 7 | { 8 | // ReSharper disable once InconsistentNaming - extensions for IEnumerable :P 9 | public static partial class IEnumerableExtensions 10 | { 11 | private static IRandom fallbackRandom; 12 | 13 | public static IRandom GetFallbackRandom() 14 | { 15 | if (fallbackRandom != null) 16 | { 17 | return fallbackRandom; 18 | } 19 | 20 | fallbackRandom = new SystemRandomWrapper( 21 | new Random((int) new DateTime().TimeOfDay.TotalMilliseconds) 22 | ); 23 | return fallbackRandom; 24 | } 25 | 26 | /// 27 | /// Return a randomly selected index within `enumerable` 28 | /// 29 | /// 30 | /// 31 | /// 32 | /// A randomly selected index within `enumerable` 33 | /// The enumerable has 0 elements in it 34 | public static int RandomIndex(this IEnumerable enumerable, IRandom random = null) 35 | { 36 | if (enumerable == null) 37 | { 38 | throw new ArgumentException("Provided null IEnumerable", nameof(enumerable)); 39 | } 40 | 41 | if (!enumerable.Any()) 42 | { 43 | throw new ArgumentException("Provided IEnumerable with 0 elements", nameof(enumerable)); 44 | } 45 | 46 | var useRandom = random ?? GetFallbackRandom(); 47 | 48 | return useRandom.Next(0, enumerable.Count()); 49 | } 50 | 51 | /// 52 | /// Return a randomly selected element within `enumerable` 53 | /// 54 | /// Enumerable to return an element from 55 | /// Optional System.Random random instance 56 | /// A randomly selected element from within `enumerable` 57 | /// The enumerable has 0 elements in it 58 | /// 59 | /// Internally used Eunomia.IEnumerableExtensions.RandomIndex method 60 | /// returns an index out of range of our enumerable 61 | /// 62 | public static T RandomElement(this IEnumerable enumerable, IRandom random = null) 63 | { 64 | if (enumerable == null) 65 | { 66 | throw new ArgumentException("Provided null IEnumerable", nameof(enumerable)); 67 | } 68 | 69 | if (!enumerable.Any()) 70 | { 71 | throw new ArgumentException("Provided IEnumerable with 0 elements", nameof(enumerable)); 72 | } 73 | 74 | var index = RandomIndex(enumerable, random); 75 | if (index >= enumerable.Count()) 76 | { 77 | throw new InvalidOperationException("RandomIndex returned an index out of range"); 78 | } 79 | 80 | return enumerable.ElementAt(index); 81 | } 82 | } 83 | } -------------------------------------------------------------------------------- /Runtime/StateMachine.md: -------------------------------------------------------------------------------- 1 | # State Machine 2 | **StateMachine** is a simple state machine. 3 | 4 | * One determines an initial state at construction 5 | 6 | ```csharp 7 | state = new StateMachine(State.Attract); 8 | ``` 9 | 10 | * One describes other states that can transitioned to from that initial state and the states that can be transitioned to from THOSE state, and so on, sometimes looping back 11 | 12 | ```csharp 13 | state.AddTransition( 14 | new StateTransition() { from = State.Attract, to = State.Interactive } 15 | ); 16 | 17 | state.AddTransitions(new[] { 18 | new StateTransition() { from = State.Interactive, to = State.InteractiveClosing }, 19 | new StateTransition() { from = State.InteractiveClosing, to = State.Attract }, 20 | ); 21 | ``` 22 | 23 | * One registers a variety of methods to respond to state changes 24 | 25 | ```csharp 26 | state.AddTransitions(new[] { 27 | new StateTransition() { 28 | from = State.Interactive, to = State.InteractiveClosing, 29 | performBeforeSync = () => {...}, performAfterSync = () => {...} 30 | }, 31 | new StateTransition() { 32 | from = State.InteractiveClosing, to = State.Attract, 33 | performBefore = async () => {...}, performAfter = async () => {...} 34 | }, 35 | ); 36 | ``` 37 | 38 | * One registers a variety of methods to respond to entering a state 39 | 40 | ```csharp 41 | state.SetPerformBeforeEnter(State.Interactive, async () => {...}); 42 | state.SetPerformBeforeEnterSync(State.Interactive, () => {...}); 43 | state.SetPerformAfterEnter(State.Interactive, async () => {...}); 44 | state.SetPerformAfterEnterSync(State.Interactive, () => {...}); 45 | ``` 46 | 47 | * One attempts to change state, with exceptions optionally. thrown for invalid attempts, such as a non-existent transition or an attempt during a previous transition. 48 | 49 | *Example:* 50 | 51 | * This works successfully because above we're currently at `State.Attract` and we've registered a transition from `Attract` to `Interactive` 52 | 53 | ```csharp 54 | state.SetState(State.Interactive); 55 | ``` 56 | 57 | This will perform all `performBefore(Enter)(Sync)` and `performAfter(Enter)(Sync)` properly. In this way we can enforce clear, consistent transition and setup of a state. 58 | 59 | 60 | * If we're now at `Interactive` this will throw an exception because there is no transition from `Interactive` directly back to `Attract`, only to `InteractiveClosing` first. 61 | 62 | ```csharp 63 | state.SetState(State.Attract); 64 | ``` 65 | 66 | In this way we can enforce only supported state changes, state changes that make sense to the object or representation we've created. 67 | 68 | 69 | ## Order of execution of registered responses: 70 | 71 | 1. Transition's async *PerformBefore* 72 | 1. Transition's sync *PerformBeforeSync* 73 | 1. New State's async *PerformBeforeEnter* 74 | 1. New State's sync *PerformBeforeEnterSync* 75 | 1. **New State made Current State** 76 | 1. Transition's async *PerformAfter* 77 | 1. Transition's sync *PerformAfterSync* 78 | 1. New State's async *PerformAfterEnter* 79 | 1. New State's sync *PerformAfterEnterSync* 80 | 81 | Because our new state becomes our current state before *PerformAfter(Enter)(Sync)* registered methods are performed technically a *PerformAfter(Enter)(Sync)* can queue another state change, just be careful we aren't still transitioning when the state change is performed! 😜 82 | -------------------------------------------------------------------------------- /Runtime/Filters/KalmanFilterFloat.cs: -------------------------------------------------------------------------------- 1 | // Based on https://gist.github.com/davidfoster/48acce6c13e5f7f247dc5d5909dce349 2 | 3 | using System.Collections.Generic; 4 | 5 | /// A Kalman filter implementation for float values. 6 | public class KalmanFilterFloat 7 | { 8 | 9 | //----------------------------------------------------------------------------------------- 10 | // Constants: 11 | //----------------------------------------------------------------------------------------- 12 | 13 | public const float DEFAULT_Q = 0.000001f; 14 | public const float DEFAULT_R = 0.01f; 15 | 16 | public const float DEFAULT_P = 1; 17 | 18 | //----------------------------------------------------------------------------------------- 19 | // Private Fields: 20 | //----------------------------------------------------------------------------------------- 21 | 22 | private float q; 23 | private float r; 24 | private float p = DEFAULT_P; 25 | private float x; 26 | private float k; 27 | 28 | //----------------------------------------------------------------------------------------- 29 | // Constructors: 30 | //----------------------------------------------------------------------------------------- 31 | 32 | // N.B. passing in DEFAULT_Q is necessary, even though we have the same value (as an optional parameter), because this 33 | // defines a parameterless constructor, allowing us to be new()'d in generics contexts. 34 | public KalmanFilterFloat() : this(DEFAULT_Q) { } 35 | 36 | public KalmanFilterFloat(float aQ = DEFAULT_Q, float aR = DEFAULT_R) 37 | { 38 | q = aQ; 39 | r = aR; 40 | } 41 | 42 | //----------------------------------------------------------------------------------------- 43 | // Public Methods: 44 | //----------------------------------------------------------------------------------------- 45 | 46 | public float Update(float measurement, float? newQ = null, float? newR = null) 47 | { 48 | 49 | // update values if supplied. 50 | if (newQ != null && q != newQ) 51 | { 52 | q = (float)newQ; 53 | } 54 | if (newR != null && r != newR) 55 | { 56 | r = (float)newR; 57 | } 58 | 59 | // update measurement. 60 | { 61 | k = (p + q) / (p + q + r); 62 | p = r * (p + q) / (r + p + q); 63 | } 64 | 65 | // filter result back into calculation. 66 | float result = x + (measurement - x) * k; 67 | x = result; 68 | return result; 69 | } 70 | 71 | public float Update(List measurements, bool areMeasurementsNewestFirst = false, float? newQ = null, float? newR = null) 72 | { 73 | 74 | float result = 0; 75 | int i = (areMeasurementsNewestFirst) ? measurements.Count - 1 : 0; 76 | 77 | while (i < measurements.Count && i >= 0) 78 | { 79 | 80 | // decrement or increment the counter. 81 | if (areMeasurementsNewestFirst) 82 | { 83 | --i; 84 | } 85 | else 86 | { 87 | ++i; 88 | } 89 | 90 | result = Update(measurements[i], newQ, newR); 91 | } 92 | 93 | return result; 94 | } 95 | 96 | public void Reset() 97 | { 98 | p = 1; 99 | x = 0; 100 | k = 0; 101 | } 102 | } -------------------------------------------------------------------------------- /Runtime/FileUtility/Read.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Text; 3 | using System.Threading.Tasks; 4 | 5 | // ReSharper disable once CheckNamespace - In folder for organization reasons 6 | namespace Eunomia 7 | { 8 | public static partial class FileUtility 9 | { 10 | /// 11 | /// Read a file, if it exists, to a string 12 | /// 13 | /// File name of the file to be read 14 | /// Contents of the file as a string 15 | /// File to read is not found 16 | public static async Task ReadFile(string fileName) 17 | { 18 | if (!File.Exists(fileName)) 19 | { 20 | throw new FileNotFoundException("Unable to find file", fileName); 21 | } 22 | 23 | // ReSharper disable once UseAwaitUsing - Not supported by Unity 2019 24 | using (var stream = File.Open(fileName, FileMode.Open)) 25 | { 26 | var buffer = new byte[stream.Length]; 27 | #pragma warning disable CA1835 // Not supported by Unity 2019 28 | await stream.ReadAsync(buffer, 0, (int)stream.Length); 29 | #pragma warning restore CA1835 30 | stream.Close(); 31 | 32 | return Encoding.Default.GetString(buffer); 33 | } 34 | } 35 | 36 | /// 37 | /// Read a file, if it exists. If it doesn't read a fallback file, if it exists 38 | /// 39 | /// File name of the file to be read 40 | /// File name of the file to be read if first file does not exist 41 | /// Contents of first file, if it exists, or contents of second file, if it exists 42 | /// First file and fallback are not found 43 | public static async Task ReadFileWithFallback(string fileName, string fallbackFileName) 44 | { 45 | try 46 | { 47 | return await ReadFile(fileName); 48 | } 49 | catch (FileNotFoundException) 50 | { 51 | return await ReadFile(fallbackFileName); 52 | } 53 | } 54 | 55 | /// 56 | /// Read a file, if it exists. If it doesn't read a fallback file, if it exists. Report back the fileName successfully 57 | /// read 58 | /// 59 | /// File name of the file to be read 60 | /// File name of the file to be read if first file does not exist 61 | /// 62 | /// Tuple of:
63 | /// 1. Contents of first file, if it exists, or contents of second file, if it exists
64 | /// and
65 | /// 2. File name of file successfully read 66 | ///
67 | /// First file and fallback are not found 68 | public static async Task<(string, string)> ReadFileWithFallbackAndFileName(string fileName, 69 | string fallbackFileName) 70 | { 71 | try 72 | { 73 | var contents = await ReadFile(fileName); 74 | return (contents, fileName); 75 | } 76 | catch (FileNotFoundException) 77 | { 78 | var contents = await ReadFile(fallbackFileName); 79 | return (contents, fallbackFileName); 80 | } 81 | } 82 | } 83 | } -------------------------------------------------------------------------------- /Tests/DispatcherTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | 5 | // ReSharper disable once CheckNamespace 6 | namespace Eunomia.Tests 7 | { 8 | [TestClass()] 9 | public class DispatcherTests 10 | { 11 | [TestMethod()] 12 | public void LogUnhandledExceptionsTest() 13 | { 14 | var dispatcher = new Dispatcher(); 15 | 16 | var count = 0; 17 | var expectedCount = new Random().Next(1000); 18 | var expectedExceptionCount = 0; 19 | for (var queuedCount = 0; queuedCount < expectedCount; queuedCount++) 20 | { 21 | dispatcher.Invoke(() => 22 | { 23 | count += 1; 24 | if (count % 2 == 0) 25 | { 26 | expectedExceptionCount += 1; 27 | throw new AssertFailedException(); 28 | } 29 | }); 30 | } 31 | 32 | var loggedCount = 0; 33 | dispatcher.logUnhandledExceptions = (exception) => { loggedCount += 1; }; 34 | 35 | dispatcher.InvokePending(); 36 | 37 | Assert.AreEqual(count, expectedCount); 38 | Assert.AreEqual(expectedExceptionCount, loggedCount); 39 | } 40 | 41 | [TestMethod()] 42 | public void CatchUnhandledExceptionsTest() 43 | { 44 | var dispatcher = new Dispatcher(); 45 | 46 | var count = 0; 47 | var expectedCount = new Random().Next(1000); 48 | for (var queuedCount = 0; queuedCount < expectedCount; queuedCount++) 49 | { 50 | dispatcher.Invoke(() => 51 | { 52 | count += 1; 53 | if (count % 2 == 0) 54 | { 55 | throw new AssertFailedException(); 56 | } 57 | }); 58 | } 59 | 60 | dispatcher.InvokePending(); 61 | 62 | Assert.AreEqual(count, expectedCount); 63 | } 64 | 65 | [TestMethod()] 66 | public void InvokeTest() 67 | { 68 | var dispatcher = new Dispatcher(); 69 | 70 | var count = 0; 71 | var expectedCount = new Random().Next(1000); 72 | for (var queuedCount = 0; queuedCount < expectedCount; queuedCount++) 73 | { 74 | dispatcher.Invoke(() => { count += 1; }); 75 | } 76 | 77 | dispatcher.InvokePending(); 78 | 79 | Assert.AreEqual(expectedCount, count); 80 | } 81 | 82 | [TestMethod()] 83 | public void InvokePendingTest() 84 | { 85 | var dispatcher = new Dispatcher(); 86 | 87 | var count = 0; 88 | var expectedCount = new Random().Next(1000); 89 | var expectedOrder = new List(expectedCount); 90 | for (var queuedCount = 0; queuedCount < expectedCount; queuedCount++) 91 | { 92 | dispatcher.Invoke(() => 93 | { 94 | count += 1; 95 | expectedOrder.Add(count); 96 | }); 97 | } 98 | 99 | dispatcher.InvokePending(); 100 | 101 | Assert.AreEqual(expectedCount, count); 102 | for (var orderIndex = 0; orderIndex < expectedOrder.Count - 1; orderIndex++) 103 | { 104 | Assert.AreEqual(expectedOrder[orderIndex], expectedOrder[orderIndex + 1] - 1); 105 | } 106 | 107 | dispatcher.InvokePending(); 108 | 109 | Assert.AreEqual(expectedCount, count); 110 | } 111 | } 112 | } -------------------------------------------------------------------------------- /Runtime/IntExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Eunomia 4 | { 5 | public static class IntExtensions 6 | { 7 | /// 8 | /// Wraps a value around 0 (inclusive) and a specified wrap around value (exclusive) 9 | /// 10 | /// Value to wrap 11 | /// Value to use to wrap around, exclusive 12 | /// Wrapped value 13 | /// `around` <= 0 14 | public static int Wrap(this int value, int around) 15 | { 16 | if (around <= 0) 17 | { 18 | throw new ArgumentOutOfRangeException(nameof(around), around, "around must be >= 0"); 19 | } 20 | 21 | if (value < 0) 22 | { 23 | return around + value; 24 | } 25 | else if (value >= around) 26 | { 27 | return value % around; 28 | } 29 | 30 | return value; 31 | } 32 | 33 | /// 34 | /// Restricts a value to be within `lower` and `upper` (inclusive) 35 | /// 36 | /// Value to wrap 37 | /// Lower value to be within, inclusive 38 | /// Upper value to be within, inclusive 39 | /// `this` updated 40 | /// `lower` > `upper` 41 | public static int Clamp(this int value, int lower, int upper) 42 | { 43 | if (lower > upper) 44 | { 45 | throw new ArgumentException($"lower ({lower}) must be less than or equal to upper ({upper})", 46 | nameof(lower)); 47 | } 48 | 49 | if (value < lower) 50 | { 51 | return lower; 52 | } 53 | else if (value > upper) 54 | { 55 | return upper; 56 | } 57 | 58 | return value; 59 | } 60 | 61 | /// `within` <= 0 62 | public static int ClampUpperExclusive(this int value, int within) 63 | { 64 | if (within <= 0) 65 | { 66 | throw new ArgumentOutOfRangeException(nameof(within), within, "within must be > 0"); 67 | } 68 | 69 | if (value < 0) 70 | { 71 | return 0; 72 | } 73 | else if (value >= within) 74 | { 75 | return within - 1; 76 | } 77 | 78 | return value; 79 | } 80 | 81 | /// 82 | /// Map a value from one range to another. Supports end values that are less than their start values 83 | /// 84 | /// Value to map 85 | /// From range start 86 | /// From range end 87 | /// To range start 88 | /// To range end 89 | /// `this` updated 90 | public static int Map(this int value, 91 | int fromStart, 92 | int fromEnd, 93 | int toStart, 94 | int toEnd 95 | ) 96 | { 97 | if (fromStart == fromEnd) 98 | { 99 | throw new ArgumentException($"fromStart ({fromStart}) must not equal fromEnd ({fromEnd})", 100 | nameof(fromStart)); 101 | } 102 | 103 | if (toStart == toEnd) 104 | { 105 | throw new ArgumentException($"toStart ({toStart}) must not equal toEnd ({toEnd})", nameof(toStart)); 106 | } 107 | 108 | return (int) ( 109 | toStart + (float) (value - fromStart) / (float) (fromEnd - fromStart) * (toEnd - toStart) 110 | ); 111 | } 112 | }; 113 | }; -------------------------------------------------------------------------------- /Runtime/FloatExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Eunomia 4 | { 5 | public static class FloatExtensions 6 | { 7 | /// 8 | /// Wraps a value around 0 and a specified wrap around value 9 | /// 10 | /// Value to wrap 11 | /// Value to use to wrap around, exclusive 12 | /// `this` updated 13 | /// `around` <= 0 14 | public static float Wrap(this float value, float around) 15 | { 16 | if (around <= 0) 17 | { 18 | throw new ArgumentOutOfRangeException(nameof(around), around, "around must be >= 0"); 19 | } 20 | 21 | if (value < 0) 22 | { 23 | return around + value; 24 | } 25 | else if (value >= around) 26 | { 27 | return value % around; 28 | } 29 | 30 | return value; 31 | } 32 | 33 | /// 34 | /// Restricts a value to be within `lower` and `upper` (inclusive) 35 | /// 36 | /// Value to wrap 37 | /// Lower value to be within, inclusive 38 | /// Upper value to be within, inclusive 39 | /// `this` updated 40 | /// If `lower` is greater than `upper` 41 | public static float Clamp(this float value, float lower, float upper) 42 | { 43 | if (lower > upper) 44 | { 45 | throw new ArgumentException( 46 | String.Format("lower ({0}) must be less than or equal to upper ({1})", lower, upper), "lower"); 47 | } 48 | 49 | if (value < lower) 50 | { 51 | return lower; 52 | } 53 | else if (value > upper) 54 | { 55 | return upper; 56 | } 57 | 58 | return value; 59 | } 60 | 61 | /// `within` <= 0 62 | public static float ClampUpperExclusive(this float value, float within) 63 | { 64 | if (within <= 0) 65 | { 66 | throw new ArgumentOutOfRangeException(nameof(within), within, "within must be > 0"); 67 | } 68 | 69 | if (value < 0) 70 | { 71 | return 0; 72 | } 73 | else if (value >= within) 74 | { 75 | return within - 1; 76 | } 77 | 78 | return value; 79 | } 80 | 81 | /// 82 | /// Map a value from one range to another. Supports end values that are less than their start values 83 | /// 84 | /// Value to map 85 | /// From range start 86 | /// From range end 87 | /// To range start 88 | /// To range end 89 | /// `this` updated 90 | public static float Map(this float value, 91 | float fromStart, 92 | float fromEnd, 93 | float toStart, 94 | float toEnd 95 | ) 96 | { 97 | // ReSharper disable once CompareOfFloatsByEqualityOperator 98 | if (fromStart == fromEnd) 99 | { 100 | throw new ArgumentException($"fromStart ({fromStart}) must not equal fromEnd ({fromEnd})", 101 | nameof(fromStart)); 102 | } 103 | 104 | // ReSharper disable once CompareOfFloatsByEqualityOperator 105 | if (toStart == toEnd) 106 | { 107 | throw new ArgumentException($"toStart ({toStart}) must not equal toEnd ({toEnd})", nameof(toStart)); 108 | } 109 | 110 | return toStart + (value - fromStart) / (fromEnd - fromStart) * (toEnd - toStart); 111 | } 112 | } 113 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # macOS index files 2 | /**/._*.* 3 | /**/._* 4 | 5 | .editorconfig 6 | bin.meta 7 | obj.meta 8 | 9 | ## Ignore Visual Studio temporary files, build results, and 10 | ## files generated by popular Visual Studio add-ons. 11 | ## 12 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 13 | 14 | # User-specific files 15 | *.rsuser 16 | *.suo 17 | *.user 18 | *.userosscache 19 | *.sln.docstates 20 | 21 | # User-specific files (MonoDevelop/Xamarin Studio) 22 | *.userprefs 23 | 24 | # Mono auto generated files 25 | mono_crash.* 26 | 27 | # Build results 28 | [Dd]ebug/ 29 | [Dd]ebugPublic/ 30 | [Rr]elease/ 31 | [Rr]eleases/ 32 | x64/ 33 | x86/ 34 | [Ww][Ii][Nn]32/ 35 | [Aa][Rr][Mm]/ 36 | [Aa][Rr][Mm]64/ 37 | bld/ 38 | [Bb]in/ 39 | [Oo]bj/ 40 | [Ll]og/ 41 | [Ll]ogs/ 42 | 43 | # Visual Studio 2015/2017 cache/options directory 44 | .vs/ 45 | # Uncomment if you have tasks that create the project's static files in wwwroot 46 | #wwwroot/ 47 | 48 | # Visual Studio 2017 auto generated files 49 | Generated\ Files/ 50 | 51 | # MSTest test Results 52 | [Tt]est[Rr]esult*/ 53 | [Bb]uild[Ll]og.* 54 | 55 | # NUnit 56 | *.VisualState.xml 57 | TestResult.xml 58 | nunit-*.xml 59 | 60 | # Build Results of an ATL Project 61 | [Dd]ebugPS/ 62 | [Rr]eleasePS/ 63 | dlldata.c 64 | 65 | # Benchmark Results 66 | BenchmarkDotNet.Artifacts/ 67 | 68 | # .NET Core 69 | project.lock.json 70 | project.fragment.lock.json 71 | artifacts/ 72 | 73 | # ASP.NET Scaffolding 74 | ScaffoldingReadMe.txt 75 | 76 | # StyleCop 77 | StyleCopReport.xml 78 | 79 | # Files built by Visual Studio 80 | *_i.c 81 | *_p.c 82 | *_h.h 83 | *.ilk 84 | *.obj 85 | *.iobj 86 | *.pch 87 | *.pdb 88 | *.ipdb 89 | *.pgc 90 | *.pgd 91 | *.rsp 92 | *.sbr 93 | *.tlb 94 | *.tli 95 | *.tlh 96 | *.tmp 97 | *.tmp_proj 98 | *_wpftmp.csproj 99 | *.log 100 | *.tlog 101 | *.vspscc 102 | *.vssscc 103 | .builds 104 | *.pidb 105 | *.svclog 106 | *.scc 107 | 108 | # Chutzpah Test files 109 | _Chutzpah* 110 | 111 | # Visual C++ cache files 112 | ipch/ 113 | *.aps 114 | *.ncb 115 | *.opendb 116 | *.opensdf 117 | *.sdf 118 | *.cachefile 119 | *.VC.db 120 | *.VC.VC.opendb 121 | 122 | # Visual Studio profiler 123 | *.psess 124 | *.vsp 125 | *.vspx 126 | *.sap 127 | 128 | # Visual Studio Trace Files 129 | *.e2e 130 | 131 | # TFS 2012 Local Workspace 132 | $tf/ 133 | 134 | # Guidance Automation Toolkit 135 | *.gpState 136 | 137 | # ReSharper is a .NET coding add-in 138 | _ReSharper*/ 139 | *.[Rr]e[Ss]harper 140 | *.DotSettings.user 141 | 142 | # TeamCity is a build add-in 143 | _TeamCity* 144 | 145 | # DotCover is a Code Coverage Tool 146 | *.dotCover 147 | 148 | # AxoCover is a Code Coverage Tool 149 | .axoCover/* 150 | !.axoCover/settings.json 151 | 152 | # Coverlet is a free, cross platform Code Coverage Tool 153 | coverage*.json 154 | coverage*.xml 155 | coverage*.info 156 | 157 | # Visual Studio code coverage results 158 | *.coverage 159 | *.coveragexml 160 | 161 | # NCrunch 162 | _NCrunch_* 163 | .*crunch*.local.xml 164 | nCrunchTemp_* 165 | 166 | # MightyMoose 167 | *.mm.* 168 | AutoTest.Net/ 169 | 170 | # Web workbench (sass) 171 | .sass-cache/ 172 | 173 | # Installshield output folder 174 | [Ee]xpress/ 175 | 176 | # DocProject is a documentation generator add-in 177 | DocProject/buildhelp/ 178 | DocProject/Help/*.HxT 179 | DocProject/Help/*.HxC 180 | DocProject/Help/*.hhc 181 | DocProject/Help/*.hhk 182 | DocProject/Help/*.hhp 183 | DocProject/Help/Html2 184 | DocProject/Help/html 185 | 186 | # Click-Once directory 187 | publish/ 188 | 189 | # Publish Web Output 190 | *.[Pp]ublish.xml 191 | *.azurePubxml 192 | # Note: Comment the next line if you want to checkin your web deploy settings, 193 | # but database connection strings (with potential passwords) will be unencrypted 194 | *.pubxml 195 | *.publishproj 196 | 197 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 198 | # checkin your Azure Web App publish settings, but sensitive information contained 199 | # in these scripts will be unencrypted 200 | PublishScripts/ 201 | 202 | # NuGet Packages 203 | *.nupkg 204 | # NuGet Symbol Packages 205 | *.snupkg 206 | # The packages folder can be ignored because of Package Restore 207 | **/[Pp]ackages/* 208 | # except build/, which is used as an MSBuild target. 209 | !**/[Pp]ackages/build/ 210 | # Uncomment if necessary however generally it will be regenerated when needed 211 | #!**/[Pp]ackages/repositories.config 212 | # NuGet v3's project.json files produces more ignorable files 213 | *.nuget.props 214 | *.nuget.targets 215 | 216 | # Nuget personal access tokens and Credentials 217 | nuget.config 218 | 219 | # Microsoft Azure Build Output 220 | csx/ 221 | *.build.csdef 222 | 223 | # Microsoft Azure Emulator 224 | ecf/ 225 | rcf/ 226 | 227 | # Windows Store app package directories and files 228 | AppPackages/ 229 | BundleArtifacts/ 230 | Package.StoreAssociation.xml 231 | _pkginfo.txt 232 | *.appx 233 | *.appxbundle 234 | *.appxupload 235 | 236 | # Visual Studio cache files 237 | # files ending in .cache can be ignored 238 | *.[Cc]ache 239 | # but keep track of directories ending in .cache 240 | !?*.[Cc]ache/ 241 | 242 | # Others 243 | ClientBin/ 244 | ~$* 245 | *~ 246 | *.dbmdl 247 | *.dbproj.schemaview 248 | *.jfm 249 | *.pfx 250 | *.publishsettings 251 | orleans.codegen.cs 252 | 253 | # Including strong name files can present a security risk 254 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 255 | #*.snk 256 | 257 | # Since there are multiple workflows, uncomment next line to ignore bower_components 258 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 259 | #bower_components/ 260 | 261 | # RIA/Silverlight projects 262 | Generated_Code/ 263 | 264 | # Backup & report files from converting an old project file 265 | # to a newer Visual Studio version. Backup files are not needed, 266 | # because we have git ;-) 267 | _UpgradeReport_Files/ 268 | Backup*/ 269 | UpgradeLog*.XML 270 | UpgradeLog*.htm 271 | ServiceFabricBackup/ 272 | *.rptproj.bak 273 | 274 | # SQL Server files 275 | *.mdf 276 | *.ldf 277 | *.ndf 278 | 279 | # Business Intelligence projects 280 | *.rdl.data 281 | *.bim.layout 282 | *.bim_*.settings 283 | *.rptproj.rsuser 284 | *- [Bb]ackup.rdl 285 | *- [Bb]ackup ([0-9]).rdl 286 | *- [Bb]ackup ([0-9][0-9]).rdl 287 | 288 | # Microsoft Fakes 289 | FakesAssemblies/ 290 | 291 | # GhostDoc plugin setting file 292 | *.GhostDoc.xml 293 | 294 | # Node.js Tools for Visual Studio 295 | .ntvs_analysis.dat 296 | node_modules/ 297 | 298 | # Visual Studio 6 build log 299 | *.plg 300 | 301 | # Visual Studio 6 workspace options file 302 | *.opt 303 | 304 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 305 | *.vbw 306 | 307 | # Visual Studio LightSwitch build output 308 | **/*.HTMLClient/GeneratedArtifacts 309 | **/*.DesktopClient/GeneratedArtifacts 310 | **/*.DesktopClient/ModelManifest.xml 311 | **/*.Server/GeneratedArtifacts 312 | **/*.Server/ModelManifest.xml 313 | _Pvt_Extensions 314 | 315 | # Paket dependency manager 316 | .paket/paket.exe 317 | paket-files/ 318 | 319 | # FAKE - F# Make 320 | .fake/ 321 | 322 | # CodeRush personal settings 323 | .cr/personal 324 | 325 | # Python Tools for Visual Studio (PTVS) 326 | __pycache__/ 327 | *.pyc 328 | 329 | # Cake - Uncomment if you are using it 330 | # tools/** 331 | # !tools/packages.config 332 | 333 | # Tabs Studio 334 | *.tss 335 | 336 | # Telerik's JustMock configuration file 337 | *.jmconfig 338 | 339 | # BizTalk build output 340 | *.btp.cs 341 | *.btm.cs 342 | *.odx.cs 343 | *.xsd.cs 344 | 345 | # OpenCover UI analysis results 346 | OpenCover/ 347 | 348 | # Azure Stream Analytics local run output 349 | ASALocalRun/ 350 | 351 | # MSBuild Binary and Structured Log 352 | *.binlog 353 | 354 | # NVidia Nsight GPU debugger configuration file 355 | *.nvuser 356 | 357 | # MFractors (Xamarin productivity tool) working folder 358 | .mfractor/ 359 | 360 | # Local History for Visual Studio 361 | .localhistory/ 362 | 363 | # BeatPulse healthcheck temp database 364 | healthchecksdb 365 | 366 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 367 | MigrationBackup/ 368 | 369 | # Ionide (cross platform F# VS Code tools) working folder 370 | .ionide/ 371 | 372 | # Fody - auto-generated XML schema 373 | FodyWeavers.xsd 374 | 375 | # VS Code files for those working on multiple tools 376 | .vscode/* 377 | !.vscode/settings.json 378 | !.vscode/tasks.json 379 | !.vscode/launch.json 380 | !.vscode/extensions.json 381 | *.code-workspace 382 | *.code-workspace.meta 383 | 384 | # Local History for Visual Studio Code 385 | .history/ 386 | 387 | # Windows Installer files from build outputs 388 | *.cab 389 | *.msi 390 | *.msix 391 | *.msm 392 | *.msp 393 | 394 | # JetBrains Rider 395 | .idea/ 396 | *.sln.iml 397 | 398 | # Unity 399 | /Scenes 400 | /Scenes.meta 401 | 402 | # macOS 403 | .DS_Store 404 | 405 | # Local tools 406 | Tools/ 407 | 408 | # Documentation 409 | /Documentation 410 | -------------------------------------------------------------------------------- /Runtime/StateMachine.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | 5 | namespace Eunomia 6 | { 7 | // TODO: should we add Main Dispatch support? 8 | /// 9 | /// Set State Order of Operations: 10 | /// 1. Test valid Transition 11 | /// 2. Transition::Perform Before 12 | /// 3. To State::Perform Before Enter 13 | /// 4. Transition::Perform After 14 | /// 5. To State::Perform After Enter 15 | /// 16 | /// 17 | public class StateMachine where TState : IEquatable, StateMachine.IState 18 | { 19 | private readonly Dictionary states = new Dictionary(); 20 | private bool currentlyTransitioning = false; 21 | private Transition currentTransition; 22 | public Action logAttemptedTransitionDuringTransition = null; 23 | public Action logInvalidStateTransition = null; 24 | public Action logTransitions = null; 25 | public Action logUnhandledExceptions = null; 26 | 27 | public bool throwIfLogged = false; 28 | 29 | public StateMachine(TState initialState) 30 | { 31 | Current = initialState; 32 | } 33 | 34 | public TState Current { get; private set; } 35 | 36 | private StateInformation GetStateInformation(TState state) 37 | { 38 | if (states.ContainsKey(state)) 39 | { 40 | return states[state]; 41 | } 42 | 43 | return null; 44 | } 45 | 46 | private StateInformation GetOrCreateStateInformation(TState state) 47 | { 48 | if (!states.ContainsKey(state)) 49 | { 50 | states[state] = new StateInformation() {state = state}; 51 | } 52 | 53 | return GetStateInformation(state); 54 | } 55 | 56 | public void AddTransition(Transition transition) 57 | { 58 | var information = GetOrCreateStateInformation(transition.from); 59 | 60 | // TODO: check for duplicates 61 | information.transitions.Add(transition); 62 | } 63 | 64 | public void AddTransitions(Transition[] transitions) 65 | { 66 | transitions.ForEach(AddTransition); 67 | } 68 | 69 | public void SetPerformBeforeEnter(TState state, Func perform) 70 | { 71 | var information = GetOrCreateStateInformation(state); 72 | 73 | // TODO: warn about overwriting 74 | information.performBeforeEnter = perform; 75 | } 76 | 77 | public void SetPerformBeforeEnterSync(TState state, Action perform) 78 | { 79 | var information = GetOrCreateStateInformation(state); 80 | 81 | // TODO: warn about overwriting 82 | information.performBeforeEnterSync = perform; 83 | } 84 | 85 | public void SetPerformAfterEnter(TState state, Func perform) 86 | { 87 | var information = GetOrCreateStateInformation(state); 88 | 89 | // TODO: warn about overwriting 90 | information.performAfterEnter = perform; 91 | } 92 | 93 | public void SetPerformAfterEnterSync(TState state, Action perform) 94 | { 95 | var information = GetOrCreateStateInformation(state); 96 | 97 | // TODO: warn about overwriting 98 | information.performAfterEnterSync = perform; 99 | } 100 | 101 | /// 102 | private Transition GetStateTransition(TState to) 103 | { 104 | try 105 | { 106 | var information = GetStateInformation(Current); 107 | if (information == null) 108 | { 109 | throw new InvalidTransitionException(Current, to); 110 | } 111 | 112 | return information.GetStateTransition(to); 113 | } 114 | catch (InvalidTransitionException exception) 115 | { 116 | logInvalidStateTransition?.Invoke(Current, to, exception); 117 | 118 | throw; 119 | } 120 | } 121 | 122 | /// 123 | /// 124 | /// 125 | public async Task SetState(TState to) 126 | { 127 | Transition transitionInProgress; 128 | bool currentThrowIfLogged; 129 | lock (this) 130 | { 131 | if (currentlyTransitioning) 132 | { 133 | var exception = new AttemptedTransitionDuringTransitionException(Current, to, currentTransition); 134 | 135 | logAttemptedTransitionDuringTransition?.Invoke(currentTransition.@from, currentTransition.to, to); 136 | 137 | if (logAttemptedTransitionDuringTransition == null || throwIfLogged) 138 | { 139 | throw exception; 140 | } 141 | } 142 | 143 | currentlyTransitioning = true; 144 | currentTransition = GetStateTransition(to); 145 | 146 | transitionInProgress = currentTransition; 147 | currentThrowIfLogged = throwIfLogged; 148 | } 149 | 150 | var unhandledExceptions = new List(); 151 | 152 | logTransitions?.Invoke(Current, to); 153 | 154 | try 155 | { 156 | await transitionInProgress.PerformBefore(); 157 | } 158 | catch (Exception exception) 159 | { 160 | logUnhandledExceptions?.Invoke(Current, to, exception); 161 | 162 | unhandledExceptions.Add(exception); 163 | } 164 | 165 | var toInformation = GetStateInformation(to); 166 | 167 | if (toInformation != null) 168 | { 169 | try 170 | { 171 | await toInformation.PerformBeforeEnter(); 172 | } 173 | catch (Exception exception) 174 | { 175 | logUnhandledExceptions?.Invoke(Current, to, exception); 176 | 177 | unhandledExceptions.Add(exception); 178 | } 179 | } 180 | 181 | // TODO: does accessing Current need to be under lock? 182 | Current = to; 183 | 184 | lock (this) 185 | { 186 | currentlyTransitioning = false; 187 | } 188 | 189 | try 190 | { 191 | await transitionInProgress.PerformAfter(); 192 | } 193 | catch (Exception exception) 194 | { 195 | logUnhandledExceptions?.Invoke(Current, to, exception); 196 | 197 | unhandledExceptions.Add(exception); 198 | } 199 | 200 | if (toInformation != null) 201 | { 202 | try 203 | { 204 | await toInformation.PerformAfterEnter(); 205 | } 206 | catch (Exception exception) 207 | { 208 | logUnhandledExceptions?.Invoke(Current, to, exception); 209 | 210 | unhandledExceptions.Add(exception); 211 | } 212 | } 213 | 214 | if (unhandledExceptions.Count > 0 && (logUnhandledExceptions == null || currentThrowIfLogged)) 215 | { 216 | throw new AggregateException(unhandledExceptions); 217 | } 218 | } 219 | 220 | public interface IState 221 | { 222 | string ToString(); 223 | } 224 | 225 | public struct Transition 226 | { 227 | // TODO: only sync and only async constructors so it isn't unclear which order they execute if you use both? 228 | public Func performBefore; 229 | public Action performBeforeSync; 230 | 231 | public TState from; 232 | public TState to; 233 | 234 | public Func performAfter; 235 | public Action performAfterSync; 236 | 237 | private static async Task Perform(Func async, Action sync) 238 | { 239 | if (async != null) 240 | { 241 | await async(); 242 | } 243 | 244 | sync?.Invoke(); 245 | } 246 | 247 | public async Task PerformBefore() 248 | { 249 | await Perform(performBefore, performBeforeSync); 250 | } 251 | 252 | public async Task PerformAfter() 253 | { 254 | await Perform(performAfter, performAfterSync); 255 | } 256 | }; 257 | 258 | private class StateInformation 259 | { 260 | public readonly List transitions = new List(); 261 | 262 | public Func performAfterEnter; 263 | public Action performAfterEnterSync; 264 | 265 | // TODO: should these be arrays? 266 | public Func performBeforeEnter; 267 | public Action performBeforeEnterSync; 268 | public TState state; 269 | 270 | /// 271 | public Transition GetStateTransition(TState to) 272 | { 273 | var findResult = transitions.Find( 274 | (transition, index) => transition.to.Equals(to) 275 | ); 276 | if (findResult.found == false) 277 | { 278 | throw new InvalidTransitionException(state, to); 279 | } 280 | 281 | return findResult.result; 282 | } 283 | 284 | private static async Task Perform(Func async, Action sync) 285 | { 286 | if (async != null) 287 | { 288 | await async(); 289 | } 290 | 291 | sync?.Invoke(); 292 | } 293 | 294 | public async Task PerformBeforeEnter() 295 | { 296 | await Perform(performBeforeEnter, performBeforeEnterSync); 297 | } 298 | 299 | public async Task PerformAfterEnter() 300 | { 301 | await Perform(performAfterEnter, performAfterEnterSync); 302 | } 303 | }; 304 | 305 | public class InvalidStateException : Exception 306 | { 307 | public readonly TState State; 308 | 309 | public InvalidStateException(TState state, TState to) 310 | : base($"Invalid state '{state.ToString()}'") 311 | { 312 | State = state; 313 | } 314 | } 315 | 316 | public class InvalidTransitionException : Exception 317 | { 318 | public readonly TState From; 319 | public readonly TState To; 320 | 321 | public InvalidTransitionException(TState from, TState to) 322 | : base($"Invalid transition from '{from.ToString()}' to '{to.ToString()}'") 323 | { 324 | From = from; 325 | To = to; 326 | } 327 | } 328 | 329 | public class AttemptedTransitionDuringTransitionException : Exception 330 | { 331 | public AttemptedTransitionDuringTransitionException(TState from, TState to, Transition currentTransition) : 332 | base( 333 | $"Attempted Transition from '{from.ToString()}' to '{to.ToString()}' during Transition '{currentTransition.from.ToString()}' to '{currentTransition.to.ToString()}S'") 334 | { 335 | this.From = from; 336 | this.To = to; 337 | this.CurrentTransition = currentTransition; 338 | } 339 | 340 | public TState From { get; } 341 | public TState To { get; } 342 | public Transition CurrentTransition { get; } 343 | } 344 | }; 345 | }; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------